简体   繁体   English

如何在 ggplot2 中为用 stat_summary 制作的线条添加图例?

[英]How can I add the legend for a line made with stat_summary in ggplot2?

Say I am working with the following (fake) data:假设我正在处理以下(假)数据:

var1 <- runif(20, 0, 30)
var2 <- runif(20, 0, 40)
year <- c(1900:1919)
data_gg <- cbind.data.frame(var1, var2, year)

I melt the data for ggplot:我融化了 ggplot 的数据:

data_melt <- melt(data_gg, id.vars='year')

and I make a grouped barplot for var1 and var2:我为 var1 和 var2 制作了一个分组条形图:

plot1 <- ggplot(data_melt, aes(as.factor(year), value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")+
  xlab('Year')+
  ylab('Density')+
  theme_light()+
  theme(panel.grid.major.x=element_blank())+
  scale_fill_manual(values=c('goldenrod2', 'firebrick2'), labels=c("Var1", 
  "Var2"))+
  theme(axis.title = element_text(size=15),
        axis.text = element_text(size=12),
        legend.title = element_text(size=13),
        legend.text = element_text(size=12))+
  theme(legend.title=element_blank())

Finally, I want to add a line showing the cumulative sum (Var1 + Var2) for each year.最后,我想添加一行显示每年的累计总和 (Var1 + Var2)。 I manage to make it using stat_summary, but it does not show up in the legend.我设法使用 stat_summary 制作它,但它没有出现在图例中。

plot1 + stat_summary(fun.y = sum, aes(as.factor(year), value, colour="sum"), 
group=1, color='steelblue', geom = 'line', size=1.5)+
scale_colour_manual(values=c("sum"="blue"))+
labs(colour="")

How can I make it so that it appears in the legend?我怎样才能让它出现在图例中?

To be precise and without being a ggplot2 expert the thing that you need to change in your code is to remove the color argument from outside the aes of the stat.summary call.准确地说,如果不是 ggplot2 专家,您需要在代码中更改的是从 stat.summary 调用的 aes 之外删除 color 参数。

stat_summary(fun.y = sum, aes(as.factor(year), value, col="sum"), group=1, geom = 'line', size=1.5)

Apparently, the color argument outside the aes function (so defining color as an argument) overrides the aesthetics mapping.显然, aes 函数外部的颜色参数(因此将颜色定义为参数)覆盖了美学映射。 Therefore, ggplot2 cannot show that mapping in the legend.因此,ggplot2 无法在图例中显示该映射。

As far as the group argument is concerned it is used to connect the points for making the line, the details of which you can read here: ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"就 group 参数而言,它用于连接制作线条的点,您可以在此处阅读其详细信息: ggplot2 折线图给出“geom_path:每个组仅包含一个观察值。您需要调整群体审美?” But it is not necessary to add it inside the aes call.但是没有必要在 aes 调用中添加它。 In fact if you leave it outside the chart will not change.事实上,如果你把它留在图表之外不会改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM