简体   繁体   English

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

[英]Plotting regression line on scatter plot using ggplot

I have a quadratic regression model. 我有一个二次回归模型。 I would like to add the model's fitted regression line to a scatter plot. 我想将模型的拟合回归线添加到散点图中。 My preference is to use ggplot2. 我的偏好是使用ggplot2。 I am able to draw the scatter plot but when I use "stat_smooth()" to specify the formula, I get the following warning and the fitted line is not drawn on the scatter plot. 我可以绘制散点图,但是当我使用“ stat_smooth()”指定公式时,会收到以下警告,并且散点图上未绘制拟合线。

Warning messages: 1: 'newdata' had 80 rows but variables found have 24 rows 2: Computation failed in stat_smooth() : arguments imply differing number of rows: 80, 24 警告消息:1:“ newdata”具有80行,但找到的变量具有24行2: stat_smooth()计算失败:参数暗示不同的行数: stat_smooth()

My code is below. 我的代码如下。 Can someone please guide me what should I do differently so that I can get fitted regression line in a scatter plot using ggplot. 有人可以指导我该怎么做,以便可以使用ggplot在散点图中拟合回归线。

Code: 码:

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 think the issue here is how you specify the quadratic formula. 我认为这里的问题是如何指定二次公式。 For the squared term you could use I(x^2) or poly(x, 2) . 对于平方项,可以使用I(x^2)poly(x, 2) For example: 例如:

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

在此处输入图片说明

here is a MWE based on "mpg" dataset: 这是一个基于“ 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