When you use the stat_smooth
function of ggplot2
, it performs the following steps:
I will use the mtcars
database, but you can easily replace it with your own.
modelo <- loess(mpg ~ hp, data = mtcars) # ajusta o modelo loess
mtcars$pred <- predict(modelo) # calcula as predicoes
ggplot (data = mtcars, aes (x = hp, y = mpg)) + geom_point() +
geom_line(aes(y = pred), colour = "blue") # plota as predicoes usando linha
See that this chart is the same as the graph made using:
ggplot (data = mtcars, aes (x = hp, y = mpg)) + geom_point() +
stat_smooth(method = "loess")
So, to get the maximum value of the curve just filter in your data.frame:
mtcars[mtcars$pred == max(mtcars$pred), ]