Plotting Quantile regression with full range in ggplot using facet_wrap

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 18:45:07

问题


So I would like to plot entire full range quantile lines in full range when using facet_wrap. The code goes as follows:

library(tidyverse)
library(quantreg)

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")
#> [multiple warnings removed for clarity]

Created on 2019-12-05 by the reprex package (v0.3.0)

As can be seen regression lines don't have full range and I cannot solve this easily.


回答1:


This feels over-engineered, but one approach would be to get the slope-intercept figures outside of ggplot and then plot them using geom_abline. A potential downside of this implementation is that it uses some jittering to prevent a "singular design matrix" error in rq, but this means that it would generate random slopes even for data with only one x value. To get around that, there's a step here to remove data from the slop calculation if it only has one value for that variable-gear combination.

mtcars %>% 
  gather("variable", "value", -c(3, 10)) -> mt_tidy

mt_tidy %>%
  # EDIT: Added section to remove data that only has one value for that
  #   variable and gear. 
  group_by(variable, gear) %>%
    mutate(distinct_values = n_distinct(value)) %>% 
    ungroup() %>%
    filter(distinct_values > 1) %>%
    select(-distinct_values) %>%

  nest_legacy(-c(variable, gear)) %>% 
  # the jittering here avoids the "Singular design matrix" error
  mutate(qtile = map(data, ~ rq(jitter(.x$disp) ~ jitter(.x$value), 
                                tau = 0.5)),
         tidied = map(qtile, broom::tidy)) %>%
  unnest_legacy(tidied) %>%
  select(gear:estimate) %>%
  pivot_wider(names_from = term, values_from = estimate) %>%
  select(gear, variable, 
         intercept = `(Intercept)`, 
         slope = `jitter(.x$value)`) -> qtl_lines

ggplot(mt_tidy, aes(value, disp, color = factor(gear))) + 
  geom_point() + 
  geom_abline(data = qtl_lines,
              aes(intercept = intercept, slope = slope,
                  color = factor(gear))) +
  facet_wrap(~variable, scales = "free")



来源:https://stackoverflow.com/questions/59192861/plotting-quantile-regression-with-full-range-in-ggplot-using-facet-wrap

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