3

My problem is that I would like to create plot with mean values and standard deviation.

I found the function plotmeans in package gplots and now I would like to add a trendline to that graph. I try to do this with abline but it is not working. I would be really grateful for some help.

My data looks like this:

year <- c(2004, 2004, 2004, 2005, 2005, 2005, 2006, 2006, 2006, 2007, 2007, 2007, 2008, 2008, 2008, 2009, 2009, 2009)
value <- c(116,114,115,110,110,109,100,99,102,95,96,95,90,91,94,70,71,73)
df <- data.frame(year, value); head(df)
library(gplots)

plotmeans(value ~ year, data= df, p = 0.99, connect= FALSE)
abline(h=c(100), col= "blue", lty= 2)
abline(lm(value ~ year, data= df))

So the first abline works OK, but the lm line not.

Andre Silva
  • 4,782
  • 9
  • 52
  • 65
Eco06
  • 531
  • 2
  • 8
  • 17

1 Answers1

5

In the plot, the values on the x-axis are recoded as factor levels. Hence you have to transform year to a factor and use its numeric values. The result is used for the lm function.

df$year2 <- as.numeric(factor(year))    

library(gplots)
plotmeans(value ~ year, data= df, p = 0.99, connect= FALSE)
abline(h=c(100), col= "blue", lty= 2)
abline(lm(value ~ year2, data= df))

enter image description here

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168