Plot quantiles of distribution in ggplot2 with facets

梦想的初衷 提交于 2019-12-06 05:39:06

You can calculate the quantiles beforehand.

Using your example data:

library (dplyr)
d2 <- df.example %>%
  group_by(model, type) %>%
  summarize(lower = quantile(value, probs = .025),
            upper = quantile(value, probs = .975))

And then plot like 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))

Use plyr (or dplyr, data.table) to precompute these values ...

set.seed(1)
# ...

df.q <- ddply(df.example, .(model, type),
              summarize, q=quantile(value, c(.025, .975)))    
p + geom_vline(aes(xintercept=q), data=df.q)

Good question. The more general version of the same question is: how do you call functions on the subsetted datasets when using facets? This seems like a very useful feature and so I searched around but could not find anything about it.

The answers already given are excellent. Another option is to use multiplot() as a way of doing the faceting manually.

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