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:
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 - add one mean trend line for different lines in one plot
But neither even result in a trend line. Examples:
p + stat_smooth( aes( y = Value, x = Period), inherit.aes = FALSE )
p + stat_summary(fun.y=mean, geom="line")
Perhaps you are looking for geom_smooth
with method = "lm"
if you are looking for a trend line?
ggplot(df, aes(x = Period, y = Value, group = Name)) +
geom_line(aes(color= Name)) +
geom_smooth(aes(group = 1), method = "lm", size = 1, se = FALSE, linetype = 2,
color = "black")