If I recall right, there isn't an exact way to extract lm()
coefficients from ggplot's geom_smoth()
function. I've tried modelling the output without ggplot, but I keep getting very different answers.
An example with the mpg
dataset:
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(method='lm', formula=y~poly(x,2))
Instead of the default loess model from geom_smooth()
I'm actively forcing a polynomial of degree 2 so I can build an equation and solve for its minimum. The output looks like it has a minimum around displ=5.75 or so.
Yet, when I try to do the modelling outside of ggplot:
test <- lm(mpg$hwy ~ poly(mpg$displ,2))
polyfun <- function(x) {coef(test)[1] + coef(test)[2]*x + coef(test)[3]*(x)^2 }
curve(polyfun, from=0, to=7)
optimize(polyfun, interval = c(0, 7), maximum = F)
I get a crazily different answer:
with the result from optimize
being: $minimum [1] 1.308562
. I'm pretty sure the form of my equation using the model coefficients is right, but the plotted equation is very wrong. Is there something obvious that I'm missing?