I am trying to plot the quantile regression lines for a set of data. I would like to extend the quantile regression lines from geom_quantile()
in order to show how they forecast similar to using stat_smooth()
with the fullrange argument set to TRUE. However, there is no fullrange argument for geom_quantile()
. As an example, see below:
data("mpg")
library(ggplot2)
library(dplyr)
m <-
ggplot(mpg, aes(displ,1/ hwy))
geom_point()
m geom_quantile()
scale_x_continuous(limits = c(1,9),
breaks = waiver(),
n.breaks = 8)
p <-
ggplot(mpg, aes(displ,1/ hwy))
geom_point()
p stat_smooth(method = lm, fullrange = TRUE, se = FALSE, color = "red")
scale_x_continuous(limits = c(1,9),
breaks = waiver(),
n.breaks = 8)
m1 <-
ggplot(mpg, aes(displ,1/ hwy))
geom_point()
m1 geom_quantile(fullrange = TRUE)
scale_x_continuous(limits = c(1,9),
breaks = waiver(),
n.breaks = 8)
The first part for m
gives the quantile regression lines over the set of data.
For p
, I can show the linear regression line forecast out to a displacement of say 9. For m1
though, I can't extend out the regression lines. Would there be a way for me to tell ggplot
to do this kind of forecast? Easier is preferable, of course, but I'll consider any suggestions. Thanks in advance!
CodePudding user response:
Under the hood, geom_quantile
uses quantreg::rq
, and it's very straightforward to use it directly to produce the same effect using geom_abline
:
mod <- quantreg::rq(I(1/hwy) ~ displ, tau = c(0.25, 0.5, 0.75), data = mpg)
r_df <- setNames(as.data.frame(t(coef(mod))), c("intercept", "gradient"))
m1 geom_abline(data = r_df, aes(slope = gradient, intercept = intercept))
scale_x_continuous(limits = c(1,9),
breaks = waiver(),
n.breaks = 8)