geom_quantile full range in ggplot2

坚强是说给别人听的谎言 提交于 2020-01-03 19:16:11

问题


Is there a way how to set full_range = T parametr somehow in ggplot?

library(ggplot2)
ggplot(mtcars, aes(hp, disp))  + 
  geom_point() + 
  #geom_smooth(method = "lm", aes(group = factor(gear), color = factor(gear)), fullrange = T)
  geom_quantile(quantiles = 0.5, aes(group = factor(gear), colour = factor(gear)), fullrange = T)

So the quantile regression line would be "as long" as when using geom_smooth above?

Is there a way how to make it work?

Also is there a way how to plot full range when using facet_wrap function

NEW MODIFIED QUESTION: Plotting Quantile regression with full range in ggplot using facet_wrap

for example say something like this:

mtcars %>% gather("variable", "value", -c(3, 10))%>% ggplot(aes(value, disp)) +
 geom_point(aes(color = factor(gear))) + 
geom_quantile(quantiles = 0.5, aes(group = factor(gear), color =factor(gear))) + facet_wrap(~variable, scales = "free")

回答1:


I looked into StatQuantile$compute_group and it turns out you can specify the xreg argument as follows:

ggplot(mtcars, aes(hp, disp))  + 
  geom_point() + 
  geom_quantile(quantiles = 0.5, aes(group = factor(gear), colour = factor(gear)),
                xseq = min(mtcars$hp):max(mtcars$hp))

Result


This is the code

statQuantile$compute_group
<ggproto method>
  <Wrapper function>
    function (...) 
f(...)

  <Inner function (f)>
    function (data, scales, quantiles = c(0.25, 0.5, 0.75), formula = NULL, 
    xseq = NULL, method = "rq", method.args = list(), lambda = 1, 
    na.rm = FALSE) 
{
    try_require("quantreg", "stat_quantile")
    if (is.null(formula)) {
        if (method == "rqss") {
            formula <- eval(substitute(y ~ qss(x, lambda = lambda)), 
                list(lambda = lambda))
            qss <- quantreg::qss
        }
        else {
            formula <- y ~ x
        }
        message("Smoothing formula not specified. Using: ", deparse(formula))
    }
    if (is.null(data$weight)) 
        data$weight <- 1
    if (is.null(xseq)) { # <-------------------------------
        xmin <- min(data$x, na.rm = TRUE)
        xmax <- max(data$x, na.rm = TRUE)
        xseq <- seq(xmin, xmax, length.out = 100)
    }
    grid <- new_data_frame(list(x = xseq))
    if (identical(method, "rq")) {
        method <- quantreg::rq
    }
    else if (identical(method, "rqss")) {
        method <- quantreg::rqss
    }
    else {
        method <- match.fun(method)
    }
    rbind_dfs(lapply(quantiles, quant_pred, data = data, method = method, 
        formula = formula, weight = weight, grid = grid, method.args = method.args))
}


来源:https://stackoverflow.com/questions/59184868/geom-quantile-full-range-in-ggplot2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!