如何在方面直方图中向 geom_vline 添加图例?

trz*_*k.p 4 r histogram facet ggplot2 vline

我使用分面视图绘制了 3 个直方图,并为均值和中值添加了 vlines。

在此处输入图片说明

我想添加一个图例来指示哪个 vline 指的是哪个统计数据。

ggplot(x, aes(x=earnw)) + geom_histogram(binwidth=100, colour="black", fill="white")  +
facet_grid(tuyear ~ .)  +
 geom_vline(data=a, aes(xintercept=earnw.mean), linetype="dashed", size=1,   color="mean") +
 geom_vline(data=b, aes(xintercept=earnw.med), linetype="dashed", size=1, color="median") +
 scale_color_manual(name = "statistics", values = c("mean" <- "red", "median" <- "blue")) +
 labs(title="Histogram for Weekly Earnings of Respondents") + 
 labs(x="Weekly Earnings of Respondents", y="Count") +
 scale_x_continuous(breaks=seq(0,3000,200),lim=c(0,3000)) 
Run Code Online (Sandbox Code Playgroud)

以下代码返回错误:

grDevices::col2rgb(colour, TRUE) 中的错误:颜色名称“mean”无效

Ric*_*ord 5

有几种方法可以做到这一点。我会总结数据集,然后将此总结提供给geom_vline. 这里使用虹膜数据集

iris.summary <- iris %>% 
  group_by(Species) %>% 
  summarise(mean.SL = mean(Sepal.Length), med.SL = median(Sepal.Length)) %>% 
  gather(key = stat, value = value, -Species)

ggplot(iris, aes(x = Sepal.Length)) + 
  geom_histogram() + 
  facet_wrap(~ Species) +
  geom_vline(data = iris.summary, aes(xintercept = value, colour = stat), linetype = "dashed")
Run Code Online (Sandbox Code Playgroud)