Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot a linear and quadratic model on the same graph?

Tags:

r

statistics

So I have 2 models for the data set that I am using:

> Bears1Fit1 <- lm(Weight ~ Neck.G)
> 
> Bears2Fit2 <- lm(Weight ~ Neck.G + I(Neck.G)^2)

I want to plot these two models on the same scatterplot. I have this so far:

> plot(Neck.G, Weight, pch = c(1), main = "Black Bears Data: Weight Vs Neck Girth", xlab = "Neck Girth (inches) ", ylab = "Weight (pounds)")
> abline(Bears1Fit1)

However, I am unsure of how I should put the quadratic model on the same graph as well. I want to be able to have both lines on the same graph.

like image 236
temsandroses Avatar asked Oct 26 '25 08:10

temsandroses


1 Answers

Here is an example with cars data set:

data(cars)

make models:

model_lm <- lm(speed ~ dist, data = cars)
model_lm2 <- lm(speed ~ dist + I(dist^2), data = cars)

make new data:

new.data <- data.frame(dist = seq(from = min(cars$dist),
                                 to = max(cars$dist), length.out = 200))

predict:

pred_lm <- predict(model_lm, newdata = new.data)
pred_lm2 <- predict(model_lm2, newdata = new.data)

plot:

plot(speed ~ dist, data = cars)
lines(pred_lm ~ new.data$dist, col = "red")
lines(pred_lm2 ~ new.data$dist, col = "blue")
legend("topleft", c("linear", "quadratic"), col = c("red", "blue"), lty = 1)

enter image description here

with ggplot2

library(ggplot2)

put all data in one data frame and convert to long format using melt from reshape2

preds <- data.frame(new.data,
                    linear = pred_lm,
                    quadratic =  pred_lm2)

preds <- reshape2::melt(preds,
                        id.vars = 1)

plot

ggplot(data = preds)+
  geom_line(aes(x = dist, y = value, color = variable ))+
  geom_point(data = cars, aes(x = dist, y = speed))+
  theme_bw()

enter image description here

EDIT: another way using just ggplot2 using two geom_smooth layers, one with the default formula y ~ x (so it need not be specified) and one with a quadratic model formula = y ~ x + I(x^2). In order to get a legend we can specify color within the aes call naming the desired entry as we want it to show in the legend.

ggplot(cars,
       aes(x = dist, y = speed)) +
  geom_point() +
  geom_smooth(method = "lm",
              aes(color = "linear"),
              se = FALSE) +
  geom_smooth(method = "lm",
              formula = y ~ x + I(x^2),
              aes(color = "quadratic"),
              se = FALSE) +
  theme_bw()

enter image description here

like image 86
missuse Avatar answered Oct 27 '25 21:10

missuse