为什么 geom_hline 不在 ggplot2 中生成图例?
Why doesn't geom_hline generate a legend in ggplot2?
我有一些代码绘制了一些值的直方图,以及一些水平线来表示要比较的参考点。但是,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)
而且我仍然没有得到传说。谁能解释为什么我的代码没有生成带有图例的图?
默认 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)
并输出:
我有一些代码绘制了一些值的直方图,以及一些水平线来表示要比较的参考点。但是,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)
而且我仍然没有得到传说。谁能解释为什么我的代码没有生成带有图例的图?
默认 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)
并输出: