Why doesn't geom_hline generate a legend in ggplot2?

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?

Asked By: Ryan C. Thompson
||

Answer #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:

Answered By: LyzandeR
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles