在ggplot2中微调传奇键的麻烦

时间:2017-01-20 13:53:16

标签: r ggplot2 legend

我尝试使用theme()guides()函数让图例键与图完全匹配。

从这个情节开始:

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

我得到了一个情节,我可以使用以下方法修改图例键:

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))))

获得所需的结果: Legend keys matching plot

但是,当绘图还包含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"))))

Plot with incorrect legend keys

要清楚:我希望代表均值的图例键显示为一条直线红线,如第一幅图,无边框,无对角线。

(我知道我可以使用stat_summary()而不是创建一个单独的数据帧,但这对我的实际项目不起作用。)

感谢您的任何建议,

拉​​塞

1 个答案:

答案 0 :(得分:3)

这可能有点像黑客,但我从geom_ribbon删除了图例,并在图例中添加了带状颜色作为点类型(pch = 15)。 颜色还不完美,但我打赌你可以管理。

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))))

Plot