[英]Trouble with fine tuning legend key in ggplot2
I'm trying to have legend keys match exactly the plot using the theme()
and guides()
functions. 我正在尝试使用
theme()
和guides()
函数使图例键与图完全匹配。
Starting with this plot: 从这个情节开始:
library(ggplot2)
data(mpg)
mpg$year <- as.numeric(mpg$year)
means <- tapply(mpg$displ, list(mpg$year), FUN = mean)
means <- as.data.frame(means)
means$year <- as.numeric(row.names(means))
names(means)[1] <- "displ"
p1 <-
ggplot(mpg, aes(x = year, y = displ)) +
geom_jitter(aes(color = "points")) +
geom_errorbar(data = means, aes(ymin = displ, ymax = displ,
color = "mean")) +
scale_x_continuous(breaks = c(1998, 2008))
p1
I get a plot where I can modify legend keys using: 我得到一个情节,我可以使用以下方法修改图例键:
p1 + theme(legend.key = element_rect(fill = NA),
legend.title = element_blank()) +
guides(color = guide_legend(override.aes =
list(shape=c(NA, 16), linetype=c(1, 0), fill = c(NA, NA))))
Getting the desired result: 获得理想的结果:
However, when the plot also contains geom_ribbon()
the same method fails: 但是,当绘图还包含
geom_ribbon()
,相同的方法失败:
p2 <-
ggplot(mpg, aes(x = year, y = displ)) +
geom_jitter(aes(color = "points")) +
geom_ribbon(aes(ymin = 3, ymax = 4, color = "ribbon"),
fill = "green", alpha = 0.5) +
geom_errorbar(data = means, aes(ymin=displ, ymax=displ,
color="mean")) +
scale_x_continuous(breaks = c(1998, 2008))
p2 + theme(legend.key = element_rect(fill = NA),
legend.title = element_blank()) +
guides(color = guide_legend(override.aes =
list(shape=c(NA, 16, NA), linetype=c(1, 0, 0),
fill = c(NA, NA, "green"))))
To be clear: I want the legend key representing the mean to show as just a straight red line, like in the first plot, no border, no diagonal. 要清楚:我希望代表均值的图例键显示为一条直线红线,就像在第一个图中,没有边框,没有对角线。
(I realize I could use stat_summary() instead of creating a separate dataframe, but that won't work for my actual project). (我意识到我可以使用stat_summary()而不是创建一个单独的数据帧,但这对我的实际项目不起作用)。
Thanks for any advice, 谢谢你的建议,
Lasse 拉塞
This might be a bit of a hack, but I removed the legend from geom_ribbon
and added the ribbon color as a point type (pch = 15) in the legend. 这可能是一个黑客,但我从
geom_ribbon
删除了图例,并在图例中添加了带状颜色作为点类型(pch = 15)。 The colors are not perfect yet, but I bet you can manage. 颜色还不完美,但我打赌你可以管理。
p2 <-
ggplot(mpg, aes(x = year, y = displ)) +
geom_jitter(aes(color = "points")) +
geom_ribbon(aes(ymin = 3, ymax = 4, color = "ribbon"),
fill = "green", alpha = 0.5, show.legend = FALSE) +
geom_errorbar(data = means, aes(ymin=displ, ymax=displ,
color="mean")) +
scale_x_continuous(breaks = c(1998, 2008))
p2 + theme(legend.key = element_rect(fill = NA),
legend.title = element_blank()) +
guides(color = guide_legend(override.aes =
list(shape=c(NA, 16, 15), linetype=c(1, 0, 0),
color = c("red", "green", "green"),
alpha = c(1,1,.5),
size = c(1,2,6))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.