简体   繁体   English

ggplot图例不使用scale_colour_manual

[英]ggplot legend not working with scale_colour_manual

I know an identical question has been asked earlier. 我知道之前已经提出了一个相同的问题。 ggplot legend - scale_colour_manual not working ggplot图例 - scale_colour_manual无效

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. 问题:在scale_colour_manual中使用scale_colour_manual时,图例未显示。

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. 任何帮助表示赞赏。

You have to use show_guide=TRUE in geom_vline (defaults to FALSE ): 您必须在geom_vline使用show_guide=TRUE (默认为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"))

情节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM