Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fitted Model Line is looking very wrong. Fitting a Quadratic Regression Line to a plot

I am trying to plot a quadratic regression line over a plot.
This is the plot currently:
enter image description here

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading