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. 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.
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
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.
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)