【问题标题】:Add regression lines from predictive values in ggplot从 ggplot 中的预测值添加回归线
【发布时间】:2016-02-14 12:24:51
【问题描述】:

我学会了用 r 绘制这种类型的图,并添加从模型预测的回归线。

## Predict values of the model##
p11=predict(model.coh1, data.frame(COH=coh1, espajpe=1:4))
p12=predict(model.coh1, data.frame(COH=coh2, espaje=1:4))

p11
       1        2        3        4 
1.996689 2.419994 2.843298 3.266602 

p12

       1        2        3        4 
1.940247 2.414299 2.888351 3.362403 

##PLOT## 
plot(espapli~espaje, mydata)
lines(1:4,p11, col="red")
lines(1:4,p12, col="green")

现在,我想使用 ggplot 做类似的事情,这可能吗?也就是说,为这些特定值引入回归线。

【问题讨论】:

  • 如果您提供可重现的示例,可以帮助您
  • 终于可以做我想做的事了。无论如何,感谢您愿意提供帮助。 :-)

标签: r


【解决方案1】:

@gennaroTedesco 使用内置的平滑方法给出了答案。我不确定是否遵循 OP。您可以通过geom_line 进行此操作

# example data
set.seed(2125)
x <- rnorm(100)
y <- 1 + 2.5 *x + rnorm(100, sd= 0.5)

lm1 <- lm(y~x)
x2 <- rnorm(100)
p1 <- predict(lm1, data.frame(x= x2), interval= "c")

library(ggplot2)

df <- data.frame(x= x2, yhat= p1[,1], lw= p1[,2], up= p1[,3])

# plot just the fitted points
ggplot(df, aes(x= x, y= yhat)) + geom_line()

# also plot the confidence interval
ggplot(df, aes(x= x, y= yhat)) + geom_line() +
  geom_line(aes(x= x, y= up, colour= "red")) +
  geom_line(aes(x= x, y= lw, colour= "red")) + 
  theme(legend.position= "none")

# only the last plot is shown

【讨论】:

  • 非常感谢!这真的帮助我做我想做的事! :-)
【解决方案2】:

一般来说,回归线可以添加到ggplot,使用函数geom_smooth。请参阅完整文档here。如果要拟合的值与一般审美中使用的值相同,那么

p <- ggplot(data, aes(x = x, y = y)
p <- p + geom_smooth(method = 'lm')

完成这项工作。否则,您需要在geom_smooth 美学中完全指定数据集和模型。

【讨论】:

  • 感谢您的回答!
猜你喜欢
  • 2021-11-03
  • 2013-03-16
  • 2018-08-28
  • 2018-06-03
  • 2021-12-16
  • 1970-01-01
  • 2021-01-14
  • 1970-01-01
相关资源
最近更新 更多