Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 打印stat_smooth函数时无法使用列表中的模型_R_Ggplot2 - Fatal编程技术网

R 打印stat_smooth函数时无法使用列表中的模型

R 打印stat_smooth函数时无法使用列表中的模型,r,ggplot2,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 = "

我试图在一个列表中绘制多个模型。然而,在绘图时,我无法将公式更改为标准的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 

这能满足你的需要吗

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