Add lines to quadratic model ggplot2


I've fit a quadratic model to my data and am able to add the regression line using base R plots, but not ggplot2.

Here's the data and code for the model:

# Data
a = c(34L, 31L, 28L, 31L, 37L, 37L, 35L, 29L, 33L, 34L, 37L, 31L, 
37L, 42L, 37L, 36L, 17L, 16L, 28L, 33L, 34L, 32L, 34L, 44L, 41L, 
46L, 45L, 9L, 14L, 21L, 20L, 35L, 35L, 34L, 16L, 30L, 32L, 32L, 
16L, 26L, 39L, 41L, 35L, 33L, 45L, 52L, 40L, 39L, 45L, 21L, 27L, 
24L, 39L, 48L, 43L, 13L, 25L, 27L, 28L, 29L, 34L, 24L, 31L, 39L, 
45L, 37L, 36L, 47L, 5L, 19L, 20L, 26L, 32L, 51L, 39L, 18L, 19L, 
33L, 32L, 33L, 31L, 32L, 20L, 40L, 46L, 47L, 46L)

b = c(153L, 186L, 218L, 226L, 246L, 103L, 102L, 91L, 133L, 125L, 
213L, 77L, 86L, 96L, 100L, 102L, 35L, 55L, 52L, 69L, 96L, 74L, 
57L, 104L, 161L, 172L, 165L, 23L, 32L, 39L, 77L, 96L, 124L, 133L, 
25L, 49L, 64L, 77L, 19L, 26L, 46L, 80L, 105L, 110L, 90L, 119L, 
124L, 76L, 91L, 40L, 59L, 45L, 78L, 100L, 104L, 21L, 76L, 71L, 
158L, 183L, 203L, 28L, 56L, 85L, 99L, 126L, 126L, 122L, 28L, 
45L, 36L, 51L, 76L, 105L, 120L, 22L, 27L, 81L, 114L, 150L, 200L, 
239L, 44L, 59L, 76L, 88L, 101L)

b2 = b^2

# Model
model = lm(a~b+b2)

# Range of x-values
sitevalues <- seq(19, 246, 0.1)
DCL_predict = predict(model, list(b=siteval, b2=siteval^2) # list of predictive values from model

# Base R plot
plot(b,a, pch=16, xlab="Station Depth (m)", ylab="DCL Depth (m)")
lines(siteval, DCL_predict, col="blue") # this is where I use the lines() fun to add to base plot
text(x=200, y=20, "r2 = 0.57")

# ggplot
  ggplot() +
  aes(x=b, y=a) +
  geom_point() +
  theme_classic() +
lines() # ? which ggplot2 function do I use?

I'm pretty sure I need to use stat_function() but I have no idea how to incorporate the sequence of x-values with the predicted values into one smooth line like with the lines() function. Any help would be greatly appreciated!

Your reprex is not plotting a line so I am not sure what you want but the essential thing withggplot is that the data must be in a data.frame.

Here are two approaches

dat1 <- data.frame(b, a)

ggplot(dat1, aes(x=b, y=a)) +
  geom_point() + geom_line() +

ggplot(dat1, aes(x=b, y=a)) +
  geom_point() +
  geom_smooth(method = lm)
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.