问题
I have a data set, for which I graphed a regression (using ggplot2
's stat_smooth
) :
ggplot(data = mydf, aes(x=time, y=pdm)) + geom_point() + stat_smooth(col="red")
I'd also like to have the quantiles (if it's simpler, having only the quartiles will do) using the same method. All I manage to get is the following :
ggplot(data = mydf, aes(x=time, y=pdm, z=surface)) + geom_point() + stat_smooth(col="red") + stat_quantile(quantiles = c(0.25,0.75))
Unfortunately, I can't put method="loess"
in stat_quantile()
, which, if I'm not mistaken, would solve my problem.
(In case it's not clear, desired behavior = non linear regressions for the quantiles, and therefore the regression for Q25 and Q75 being below and above (respectively) my red curve (and Q50, if plotted, would be my red curve)).
Thanks
回答1:
stat_quantile
is, by default, plotting best-fit lines for the 25th and 75th percentiles at each x-value. stat_quantile
uses the rq
function from the quantreg
package (implicitly, method="rq"
in the stat_quantile
call). As far as I know, rq
doesn't do loess regression. However, you can use other flexible functions for the quantile regression. Here are two examples:
B-Spline:
library(splines)
stat_quantile(formula=y ~ bs(x, df=4), quantiles = c(0.25,0.75))
Second-Order Polynomial:
stat_quantile(formula=y ~ poly(x, 2), quantiles = c(0.25,0.75))
stat_quantile
is still using rq
, but rq
accepts formulas of the type listed above (if you don't supply a formula, then stat_quantile
is implicitly using formula=y~x
). If you use the same formula in geom_smooth
as for stat_quantile
, you'll have consistent regression methods being used for the quantiles and for the mean expectation.
来源:https://stackoverflow.com/questions/36315152/continuous-quantiles-of-a-scatterplot