简体   繁体   English

从ggplot中的预测值添加回归线

[英]Add regression lines from predictive values in ggplot

I've learnt to do this type of plots with r, and add this regression lines predicted from a model. 我学会了用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")

Now, I would like to do something similar using ggplot, is that possible? 现在,我想使用ggplot做类似的事情,这可能吗? That is, introducing a regression line for these particular values. 也就是说,为这些特定值引入回归线。

@gennaroTedesco gives an answer using the built in smoothing method. @gennaroTedesco使用内置的平滑方法给出了答案。 I'm not sure that follows the OP. 我不确定遵循OP。 You can do this via geom_line 您可以通过geom_line完成此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

在此处输入图片说明

As a general rule regression lines can be added to ggplot making use of the function geom_smooth . 作为一般规则,可以添加回归线到ggplot利用所述函数的geom_smooth Please see full documentation here . 在此处查看完整的文档。 If the values to be fitted are the same ones used in the general aesthetic, then 如果要拟合的值与一般美学中使用的值相同,则

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

does the job. 做这份工作。 Otherwise you need to fully specify the set of data and the model in the geom_smooth aesthetics. 否则,您需要在geom_smooth美学中完全指定数据集和模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM