library(ggplot2)
library(dplyr)
library(scales)
library(distributional)
theme_set(theme_ggdist())
# NOTE: cut_cdf_qi() used to be the recommended way to do intervals overlaid
# on densities, like this...
tibble(x = dist_normal(0, 1)) %>%
ggplot(aes(xdist = x)) +
stat_slab(
aes(fill = after_stat(cut_cdf_qi(cdf)))
) +
scale_fill_brewer(direction = -1)
# ... however this is now more easily and flexibly accomplished by directly
# mapping .width or level onto fill:
tibble(x = dist_normal(0, 1)) %>%
ggplot(aes(xdist = x)) +
stat_slab(
aes(fill = after_stat(level)),
.width = c(.66, .95, 1)
) +
scale_fill_brewer()
# See vignette("slabinterval") for more examples. The remaining examples
# below using cut_cdf_qi() are kept for posterity.
# With a halfeye (or other geom with slab and interval), NA values will
# show up in the fill scale from the CDF function applied to the internal
# interval geometry data and can be ignored, hence na.translate = FALSE
tibble(x = dist_normal(0, 1)) %>%
ggplot(aes(xdist = x)) +
stat_halfeye(aes(
fill = after_stat(cut_cdf_qi(cdf, .width = c(.5, .8, .95, 1)))
)) +
scale_fill_brewer(direction = -1, na.translate = FALSE)
# we could also use the labels parameter to apply nicer formatting
# and provide a better name for the legend, and omit the 100% interval
# if desired
tibble(x = dist_normal(0, 1)) %>%
ggplot(aes(xdist = x)) +
stat_halfeye(aes(
fill = after_stat(cut_cdf_qi(
cdf,
.width = c(.5, .8, .95),
labels = percent_format(accuracy = 1)
))
)) +
labs(fill = "Interval") +
scale_fill_brewer(direction = -1, na.translate = FALSE)
Run the code above in your browser using DataLab