ggplot legend not working with scale_colour_manual

久未见 提交于 2020-01-11 05:46:09

问题


I know an identical question has been asked earlier. ggplot legend - scale_colour_manual not working

But the question involves a somewhat complicated dataset than what I have here and the answer suggests restructuring data and then works with restructured data. But the problem persists even with simple data as I have below and I can't solve it. So please don't mark it as duplicate.

The problem: when using scale_colour_manual in ggplot2, the legend is not showing.

p <- data.frame(a = runif(10, 1, 2))
ggplot(data=p, aes(x=a)) +
  geom_histogram() +
  geom_vline(aes(xintercept=mean(p$a), colour="mea")) +
  geom_vline(aes(xintercept=median(p$a), colour="med")) +
  scale_colour_manual(name="Statistic",
                      values=c("med"= "red", "mea"="green"))

Any help is appreciated.


回答1:


You have to use show_guide=TRUE in geom_vline (defaults to FALSE):

p <- data.frame(a = runif(10, 1, 2))
ggplot(data=p, aes(x=a)) +
  geom_histogram() +
  geom_vline(aes(xintercept=mean(a), colour="mea"), show_guide=TRUE) +
  geom_vline(aes(xintercept=median(a), colour="med"), show_guide=TRUE) +
  scale_colour_manual(name="Statistic",
                      values=c("med"= "red", "mea"="green"))



来源:https://stackoverflow.com/questions/33768613/ggplot-legend-not-working-with-scale-colour-manual

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!