将图例添加到geom_vline [英] Add legend to geom_vline

查看:146
本文介绍了将图例添加到geom_vline的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道之前曾有人问过这个问题,但是解决方案似乎对我不起作用.

I know that this question has been asked before but the solutions don't seem to work for me.

我想做的是在直方图上用不同的颜色表示我的中位数,均值,上下分位数,然后在图上添加图例.到目前为止,这就是我想要的,并且我尝试使用scale_color_manualscale_color_identity给我一个图例.似乎没有任何作用.

What I want to do is represent my median, mean, upper and lower quantiles on a histogram in different colours and then add a legend to the plot. This is what I have so far and I have tried to use scale_color_manual and scale_color_identity to give me a legend. Nothing seems to be working.

quantile_1 <- quantile(sf$Unit.Sales, prob = 0.25)
quantile_2 <- quantile(sf$Unit.Sales, prob = 0.75)

ggplot(aes(x = Unit.Sales), data = sf) + 
  geom_histogram(color = 'black', fill = NA) + 
  geom_vline(aes(xintercept=median(Unit.Sales)),
            color="blue", linetype="dashed", size=1) + 
  geom_vline(aes(xintercept=mean(Unit.Sales)),
            color="red", linetype="dashed", size=1) +
  geom_vline(aes(xintercept=quantile_1), color="yellow", linetype="dashed", size=1)

推荐答案

您需要在aes中映射颜色:

ggplot(aes(x = Sepal.Length), data = iris) + 
  geom_histogram(color = 'black', fill = NA) + 
  geom_vline(aes(xintercept=median(iris$Sepal.Length),
                 color="median"), linetype="dashed",
             size=1) +
  geom_vline(aes(xintercept=mean(iris$Sepal.Length),
                 color="mean"), linetype="dashed",
             size=1) +
  scale_color_manual(name = "statistics", values = c(median = "blue", mean = "red"))

这篇关于将图例添加到geom_vline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆