3
votes

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?

1
Thanks Henrik. I have tried that way, but couldn't make it work. Does it work to you? - Filippo Marolla
If you try : stat_summary(fun.y = sum, aes(as.factor(year), value, col="sum", group=1), geom = 'line', size=1.5) ? - User2321
It works, thank you very much! I see the only difference is that you placed group=1 within the brackets. Maybe it's not that clear to me what group= is for...an explanation would be highly appreciated. Thanks. - Filippo Marolla

1 Answers

3
votes

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.