简体   繁体   中英

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:

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

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

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?

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)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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