问题
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