【问题标题】:Why doesn't geom_hline generate a legend in ggplot2?为什么 geom_hline 不在 ggplot2 中生成图例?
【发布时间】:2015-09-28 23:23:17
【问题描述】:

我有一些代码绘制了一些值的直方图,以及一些水平线来表示要比较的参考点。但是, ggplot 不会为线条生成图例。

library(ggplot2)
library(dplyr)

## Siumlate an equal mix of uniform and non-uniform observations on [0,1]
x <- data.frame(PValue=c(runif(500), rbeta(500, 0.25, 1)))
y <- c(Uniform=1, NullFraction=0.5) %>% data.frame(Line=names(.) %>% factor(levels=unique(.)), Intercept=.)
ggplot(x) +
    aes(x=PValue, y=..density..) + geom_histogram(binwidth=0.02) +
    geom_hline(aes(yintercept=Intercept, group=Line, color=Line, linetype=Line),
               data=y, alpha=0.5)

我什至尝试将问题简化为仅绘制线条:

ggplot(y) +
    geom_hline(aes(yintercept=Intercept, color=Line)) + xlim(0,1)

我仍然没有得到传说。谁能解释为什么我的代码没有生成带有图例的图?

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    默认情况下show_guide = FALSE 对应geom_hline。如果你打开它,那么图例就会出现。此外,alpha 需要在aes 内,否则线条的颜色将无法正确绘制(在图例上)。代码如下所示:

    ggplot(x) +
      aes(x=PValue, y=..density..) + geom_histogram(binwidth=0.02) +
      geom_hline(aes(yintercept=Intercept, colour=Line, linetype=Line, alpha=0.5),
                 data=y, show_guide=TRUE) 
    

    然后输出:

    【讨论】:

      猜你喜欢
      • 2014-05-18
      • 1970-01-01
      • 2016-10-23
      • 2017-04-19
      • 1970-01-01
      • 2014-01-21
      • 2018-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多