Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add Mean Trend Line to geom_line plot + R

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")

>Solution :

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")

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading