0

Hi I would like to know how can I retrieve the equation of stat_smooth either in the ggplot2 or in a vector or somewhere else. the code that I am using is:

p <- ggplot(data = mtcars, aes(x = disp, y = drat)) 
p <- p + geom_point() + stat_smooth(method="loess") 
p

Thanks

V.MAT
  • 55
  • 2
  • 10

1 Answers1

2

The ggpmisc package can be very usefull. However, it will not work with loess as loess doesn't give a formula. See here: Loess Fit and Resulting Equation

library(ggplot2)
library(ggpmisc)
p <- ggplot(data = mtcars, aes(x = disp, y = drat)) +
  geom_point() + 
  geom_smooth(method="lm", formula=y~x) +
  stat_poly_eq(parse=T, aes(label = ..eq.label..), formula=y~x)
p

enter image description here

MikolajM
  • 354
  • 1
  • 8
  • So is there any other alternative to the loess function? or not – V.MAT Jun 20 '17 at 09:25
  • loess is rather a visualization of the trend in your data. if you want a equation than I would recommend applying regression techniques like linear models, polynomial regression or generalized adaptive models (GAM). However in most cases you will need to define _a priori_ what is the relationship between your data eg y~x or y~x+x^2. Here is nice disscussion regarding you question: [link](https://stackoverflow.com/questions/7550582/when-to-choose-nls-over-loess) – MikolajM Jun 20 '17 at 09:59