r - Plot quantiles of distribution in ggplot2 with facets -
i'm plotting number of different distributions of first differences number of regression models in ggplot. facilitate interpretation of differences, want mark 2.5% , 97.5% percentile of each distribution. since doing quite few plots, , because data grouped in 2 dimension (model , type), define , plot respective percentiles in ggplot environment. plotting distributions using facets gets me want except percentiles. of course more manually, ideally want find solution still able use facet_grid
, since spared me lot of hassle trying fit different plots together.
here's example using simulated data:
df.example <- data.frame(model = rep(c("a", "b"), length.out = 500), type = rep(c("t1", "t2", "t2", "t1"), length.outh = 250), value = rnorm(1000)) ggplot(df.example, aes(x = value)) + facet_grid(type ~ model) + geom_density(aes(fill = model, colour = model))
i've tried add quantiles in 2 ways. first 1 produces error message:
ggplot(df.example, aes(x = value)) + facet_grid(. ~ model) + geom_density(aes(fill = model, colour = model)) + geom_vline(aes(x = value), xintercept = quantile(value, probs = c(.025, .975)))
error in quantile(value, probs = c(0.025, 0.975)) : object 'value' not found
while second 1 gets me quantiles the complete variable , not sub-densities. is, plotted quantiles identical 4 densities.
ggplot(df.example, aes(x = value)) + facet_grid(type ~ model) + geom_density(aes(fill = model, colour = model)) + geom_vline(xintercept = quantile(df.example$value, probs = c(.025, .975)))
i consequently wonder if there way plot specific quantiles each subgroup within ggplot2 environment?
greatly appreciate input.
you can calculate quantiles beforehand.
using example data:
library (dplyr) d2 <- df.example %>% group_by(model, type) %>% summarize(lower = quantile(value, probs = .025), upper = quantile(value, probs = .975))
and plot this:
ggplot(df.example, aes(x = value)) + facet_grid(type ~ model) + geom_density(aes(fill = model, colour = model)) + geom_vline(data = d2, aes(xintercept = lower)) + geom_vline(data = d2, aes(xintercept = upper))
Comments
Post a Comment