Use geom_smooth with transformed y

2019-05-03 07:57发布

问题:

Is there a way to use geom_smooth when the y variable in the formula is transformed? For example:

#This works:
 myplot <- qplot(speed, dist, data=cars)
(myplot + geom_smooth(method="lm", formula=y~log(x)))

#does not work
(myplot + geom_smooth(method="lm", formula=log(y)~x))

What I am after is a line like this:

myplot + geom_line(aes(x=speed, y=exp(predict(lm(log(dist)~speed)))))

回答1:

You can fit a GLM for Gaussian (normally distributed) data and a log link. This will allow stat_smooth to use and return the appropriate predictions

(myplot + geom_smooth(method = "glm", formula = y~x,
                      family = gaussian(link = 'log')))



标签: r ggplot2