添加回归线到plot(plotmeans)

时间:2012-11-23 14:42:56

标签: r plot linear-regression mean gplots

我的问题是我想用平均值和标准差创建图。

我在包plotmeans中找到了函数gplots,现在我想在该图表中添加趋势线。我尝试使用abline执行此操作,但它无效。我真的很感激你的帮助。

我的数据如下:

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

所以第一个abline工作正常,但lm行没有。

1 个答案:

答案 0 :(得分:5)

在图中,x轴上的值被重新编码为因子水平。因此,您必须将year转换为因子并使用其数值。结果用于lm函数。

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