繁体   English   中英

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

[英]Plotting regression line on scatter plot using ggplot

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

警告消息:1:“ newdata”具有80行,但找到的变量具有24行2: stat_smooth()计算失败:参数暗示不同的行数: stat_smooth()

我的代码如下。 有人可以指导我该怎么做,以便可以使用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)

我认为这里的问题是如何指定二次公式。 对于平方项,可以使用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")

在此处输入图片说明

这是一个基于“ mpg”数据集的MWE:

library(ggplot2)

ggplot(mpg, aes(x = hwy, y = displ)) + 
  geom_point(shape = 1) + 
  geom_smooth(method = lm, se = FALSE)

暂无
暂无

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

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