rggplot2bar-charttrendline

Creating a trendline on a bar plot with ggplot2 in R


I am trying to create a bar plot with a solid straight trendline but can't get the trendline to appear.

I am using the ggplot2 package and here is my current code for the bar plot:

library(ggplot2)

ggplot(mydf, aes(x=round, y=means, fill=round)) +
  geom_smooth(method=lm, se=FALSE, col="black", linewidth=2) + 
  geom_bar(stat="identity", color="black", position=position_dodge()) + 
  geom_errorbar(aes(ymin=means-se, ymax=means+se), width=.2, position=position_dodge(.9),) +
  theme_classic() + 
  xlab("Round") + 
  ylab("Bead Mass (g)") + 
  ggtitle("Verbal") + 
  theme(legend.position="none") + 
  geom_smooth(method=lm, se=FALSE, col="black", linewidth=2)

I'm not sure why the geom_smooth() section is not working. Any ideas? See graph for what the output looks like enter image description here


Solution

  • Two things stop the smooth being plotted, the first is that the x axis appears to be a factor, so it needs to be converted to a numeric variabke, the second is that ggplot will automatically treat different fill (from a factor) as separate groups, so this needs to be overwritten for the smooth layer, giving:

    library(ggplot2)
    
    #Example data similar to the plot shown
    mydf <- data.frame(round=factor(1:5), means=c(102, 75, 73, 95, 120), se=15)
    
    ggplot(mydf, aes(x=as.numeric(round), y=means, fill=round)) +
       geom_bar(stat="identity", color="black", position=position_dodge()) + 
      geom_errorbar(aes(ymin=means-se, ymax=means+se), width=.2, position=position_dodge(.9),) +
      theme_classic() + 
      xlab("Round") + 
      ylab("Bead Mass (g)") + 
      ggtitle("Verbal") + 
      theme(legend.position="none") + 
      geom_smooth(aes(fill=NULL),  method=lm, se=FALSE, col="black", linewidth=2)
    

    Example output