Why doesn't geom_hline generate a legend in ggplot2?

筅森魡賤 提交于 2019-12-13 15:58:50

问题


I have some code that is plots a histogram of some values, along with a few horizontal lines to represent reference points to compare against. However, ggplot is not generating a legend for the lines.

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)

I even tried reducing the problem to just plotting the lines:

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

and I still don't get a legend. Can anyone explain why my code isn't producing plots with legends?


回答1:


By default show_guide = FALSE for geom_hline. If you turn this on then the legend will appear. Also, alpha needs to be inside of aes otherwise the colours of the lines will not be plotted properly (on the legend). The code looks like this:

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) 

And output:



来源:https://stackoverflow.com/questions/32833290/why-doesnt-geom-hline-generate-a-legend-in-ggplot2

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