在绘制stat_smooth函数时无法在列表中使用模型

时间:2017-05-12 20:32:56

标签: r ggplot2

我试图在列表中绘制多个模型。然而,当绘图我无法将公式更改为标准y~x表示法时,我得到一个错误。通过一个例子可以很好地解释这一点。我如何使用模型进行绘图。

xvar=1:100
yvar=(1:100+(1:100)^2)
df=data.frame(xvar,yvar)
## this works fine
ggplot(df, aes(x=xvar, y=yvar)) + geom_point(size = 1) + geom_smooth(data = df, method = "lm", aes(x=xvar,y=yvar), formula = as.formula(y ~ x), size = 1, se = FALSE, colour = "yellow")

models=list(
    lm(yvar~xvar, data = df),
    lm(yvar~I(xvar^2), data = df)
)

ggplot(df, aes(x = xvar, y = yvar)) + geom_point(size = 1) + geom_smooth(data = df, method = "lm", aes(x=xvar,y=yvar), formula = as.formula(models[[1]]), size = 1, se = FALSE, colour = "yellow")

Warning messages:
1: 'newdata' had 80 rows but variables found have 100 rows 
2: Computation failed in `stat_smooth()`:
arguments imply differing number of rows: 80, 100 

1 个答案:

答案 0 :(得分:0)

这能满足您的需求吗?

library(ggplot2)

xvar=1:100
yvar=(1:100+(1:100)^2)
df=data.frame(xvar,yvar)
## this works fine
ggplot(df, aes(x=xvar, y=yvar)) + geom_point(size = 1) + geom_smooth(data = df, method = "lm", aes(x=xvar,y=yvar), formula = as.formula(y ~ x), size = 1, se = FALSE, colour = "yellow")

#name the models
models=list(
  m1 = lm(yvar~xvar, data = df),
  m2 = lm(yvar~I(xvar^2), data = df)
)
#use the name of the first model and then a formula
ggplot(df, aes(x = xvar, y = yvar)) + geom_point(size = 1) + geom_smooth(data = models[[c("m1","model")]], method = "lm", aes(x=xvar,y=yvar), formula = as.formula(y ~ x), size = 1, se = FALSE, colour = "yellow")