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?