如何在ggplot2中为用stat_summary制作的行添加图例? [英] How can I add the legend for a line made with stat_summary in ggplot2?

查看:86
本文介绍了如何在ggplot2中为用stat_summary制作的行添加图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我正在处理以下(伪)数据:

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)

我融化了ggplot的数据:

I melt the data for ggplot:

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

然后我为var1和var2创建了一个分组的barplot:

and I make a grouped barplot for var1 and 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())

最后,我想添加一行以显示每年的累计金额(Var1 + Var2).我设法使用stat_summary来制作它,但是它没有显示在图例中.

Finally, I want to add a line showing the cumulative sum (Var1 + Var2) for each year. I manage to make it using stat_summary, but it does not show up in the legend.

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?

推荐答案

准确地说,没有ggplot2专家,您需要更改代码的事情是从stat的aes外部删除color参数.摘要通话.

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.

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

显然,在es函数之外的color参数(因此将color定义为参数)覆盖美学外观映射.因此,ggplot2无法在图例中显示该映射.

Apparently, the color argument outside the aes function (so defining color as an argument) overrides the aesthetics mapping. Therefore, ggplot2 cannot show that mapping in the legend.

就组参数而言,它用于连接直线的点,您可以在此处阅读其详细信息:但是没有必要将其添加到aes调用中.实际上,如果将其保留在图表之外,则不会更改.

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?" But it is not necessary to add it inside the aes call. In fact if you leave it outside the chart will not change.

这篇关于如何在ggplot2中为用stat_summary制作的行添加图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆