使用 ggplot 在散点图上绘制回归线

Sol*_*oly 1 plot r ggplot2

我有一个二次回归模型。我想将模型的拟合回归线添加到散点图。我的偏好是使用 ggplot2。我能够绘制散点图,但是当我使用“stat_smooth()”来指定公式时,我收到以下警告,并且散点图上没有绘制拟合线。

警告消息:1:'newdata' 有 80 行,但发现的变量有 24 行 2:计算失败stat_smooth():参数暗示不同的行数:80、24

我的代码如下。有人可以指导我我应该做些什么不同的事情,以便我可以使用 ggplot 在散点图中获得拟合回归线。

代码:

library(gamair)
library(ggplot2)
data(hubble)

names(hubble)[names(hubble) == "y"] <- c("velocity")
names(hubble)[names(hubble) == "x"] <- c("distance")

hubble$distance.sqr <- hubble$distance^2
model2.formula <- hubble$velocity ~ hubble$distance + 
   hubble$distance.sqr - 1
model2.hbl <- lm(model2.formula, data = hubble)
summary(model2.hbl)

model2.sp <- ggplot(hubble, aes(x = distance, y = velocity)) +
  geom_point() + labs(title = "Scatter Plot between Distance & Velocity", 
  x = "Distance", y = "Velocity")
model2.sp + stat_smooth(method = "lm", formula = hubble$velocity ~ 
  hubble$distance + hubble$distance.sqr - 1)
Run Code Online (Sandbox Code Playgroud)

nei*_*fws 5

我认为这里的问题是你如何指定二次公式。对于平方项,您可以使用I(x^2)poly(x, 2)。例如:

ggplot(hubble, aes(x, y)) + 
  geom_point() + 
  stat_smooth(method = "lm", 
              formula = y ~ x + poly(x, 2) - 1) + 
  labs(x = "Distance", y = "Velocity")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明