我有一些代码绘制了一些值的直方图,以及一些水平线来表示要比较的参考点.但是,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)
Run Code Online (Sandbox Code Playgroud)
我甚至尝试将问题简化为仅绘制线条:
ggplot(y) +
geom_hline(aes(yintercept=Intercept, color=Line)) + xlim(0,1)
Run Code Online (Sandbox Code Playgroud)
我仍然没有得到一个传奇.任何人都可以解释为什么我的代码不会生成带有图例的情节吗?
默认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)
Run Code Online (Sandbox Code Playgroud)
并输出: