在R中使用ggplot绘制现有模型对象

时间:2018-11-07 18:19:03

标签: r ggplot2

是否有一种方法可以从ggplot中的现有模型对象绘制一条线而无需重新创建模型?

例如,使用mpg数据,我可以使用geom_smooth在ggplot中绘制模型:

ggplot(data = mpg, aes(x=displ, y=hwy))+
      geom_point()+
      geom_smooth(formula = y~x, method = "lm", se = FALSE, color = "blue")+
      geom_smooth(formula = y~x + I(x^2), method = "lm", se= FALSE, color = "red")

enter image description here 但是我无法弄清楚如何使用现有的模型对象绘制相似的图。如果我有2个现有模型,即fit1和fit2,如何将它们添加到图中,而无需在ggplot调用中重新拟合模型?

fit1 <- lm(hwy~displ, data = mpg)
fit2 <- lm(hwy~displ+I(displ^2), data = mpg)    
ggplot(data = mpg, aes(x=displ, y=hwy))+
      geom_point()+
      fit1 + # what goes here?
      fit2 # and here?

我遇到了使用geom_abline()的解决方案,并使用coef(fit1)[{1]和coef(fit2)[[2]]拉出坡度并进行拦截,但是如果有您正在查看的模型除了严格线性之外,还包括其他任何东西,如果要将其嵌入到函数中,则必须事先了解模型的格式,更不用说您实际上是在ggplot中重新构建模型呼叫。

0 个答案:

没有答案