I am trying to plot a quadratic regression line over a plot. This is the plot currently:
This is the code I have tried: I think it is quite self explanatory with the picture.
model7<-lm(count~distance I(distance^2), data=data)
summary(model7)
plot(count~distance, data=data)
lines(fitted(model7))
CodePudding user response:
You could make a new dataframe and then add it to the plot as a line. Here is an example with ggplot2
instead of base R plots:
library(tidyverse)
#test data
set.seed(235)
data <- tibble(distance = sample(0:600, 30),
count = (1e-6*distance-1e-5*(distance-300)^2 1) runif(30))
#model
model7<-lm(count~distance I(distance^2), data=data)
#plot
ggplot(data, aes(distance, count))
geom_point()
geom_line(data = tibble(distance = seq(0,600, by = 1))|>
(\(d) mutate(d, count = predict(model7, d)))())
Here is an update with Base R graphics:
#model line
fit_line <- data.frame(distance = seq(0,600, by = 1))
fit_line$count <- predict(model7, fit_line)
#plot
plot(count~distance, data=data)
lines(count~distance, data=fit_line)