Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 725
Filippo Marolla Avatar asked Oct 18 '25 14:10

Filippo Marolla


1 Answers

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.

like image 62
User2321 Avatar answered Oct 21 '25 03:10

User2321



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!