library(tidyverse)
library(ggdist)
library(ggpattern)
# Just look at a few categories
diamonds_small <- diamonds %>%
filter(cut %in% c("Fair", "Good", "Very Good"))
# Manually calculate summary statistics since we can't use stat_pointinterval()
# and instead have to use geom_pointinterval()
diamonds_summary <- diamonds_small %>%
group_by(cut) %>%
median_qi(price, .width = c(0.5, 0.8, 0.95))
# Plot!
diamonds_small %>%
ggplot(aes(x = price, fill = cut, pattern_fill = cut)) +
geom_density_pattern(
aes(y = after_stat(density * 1e5)), # Scale this up so that the pointinterval fits on the plot
pattern = "stripe", # Stripes
pattern_density = 0.5, # Take up 50% of the pattern (i.e. stripes equally sized)
pattern_spacing = 0.2, # Thicker stripes
pattern_size = 0, # No border on the stripes
trim = TRUE, # Trim the ends of the distributions
linewidth = 0 # No border on the distributions
) +
# Add 50%, 80%, and 95% intervals + median
geom_pointinterval(data = diamonds_summary, aes(x = price, xmin = .lower, xmax = .upper)) +
# Set colors for fills and pattern fills
scale_fill_manual(values = c("red", "blue", "orange")) +
scale_pattern_fill_manual(values = colorspace::lighten(c("red", "blue", "orange"), 0.1)) +
# Turn off legends
guides(fill = "none", pattern_fill = "none") +
labs(y = NULL) +
# Need to facet because the y-axis doesn't use categories like stat_halfeye() or ggridges
facet_wrap(vars(cut), ncol = 1) +
# Turn off the y-axis and make some other theme tweaks
theme_minimal() +
theme(axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
strip.text = element_text(face = "bold", hjust = 0))
Created on 2023-05-11 with reprex v2.0.2