Home > Enterprise >  Add Mean Trend Line to geom_line plot R
Add Mean Trend Line to geom_line plot R

Time:11-03

I need to add an average trend line to a geom_line line plot in R. The result should be a dotted line on the same chart that that is the average of the values that make up the other lines, like so:

enter image description here

Here is my example code to make the chart:

df <- data.frame(Name = c("Jim","Bob","Sue","Sally","Jim","Bob","Sue","Sally","Jim","Bob","Sue","Sally"),
                       Period = c("P1","P1","P1","P1","P2","P2","P2","P2","P3","P3","P3","P3"),
                       Value = c(150, 200, 325, 120, 760,245,46,244,200, 325, 120, 760)
                       )

p<-ggplot(df, aes(x=Period, y=Value, group=Name))  
  geom_line(aes(color=Name))

p

I tried both solutions offered in a similar question, here - enter image description here

CodePudding user response:

You could use group = 1 in your aes of the stat_summary to add a mean line for all data like this:

library(ggplot2)
p<-ggplot(df, aes(x=Period, y=Value, group=Name))  
  geom_line(aes(color=Name))
p   stat_summary(fun=mean, geom="line", lwd = 1, linetype ='longdash', aes(group=1))

Created on 2022-11-02 with reprex v2.0.2

  • Related