# Basic example with geom_bar_diverging
library(ggplot2)
library(dplyr)
library(tidyr)
set.seed(123)
df_6cat <- data.frame(matrix(sample(1:6, 600, replace = TRUE), ncol = 6)) |>
mutate_all(~ ordered(., labels = c("+++", "++", "+", "-", "--", "---"))) |>
pivot_longer(cols = everything())
ggplot(df_6cat, aes(y = name, fill = value)) +
geom_bar_diverging() + # Bars
stat_diverging() + # Labels
scale_x_continuous_diverging() + # Scale
theme_classic()
ggplot(df_6cat, aes(y = name, fill = value)) +
geom_bar_diverging() + # Bars
stat_diverging(totals_by_direction = TRUE, nudge_label_outward = 0.05) + # Totals as Label
scale_x_continuous_diverging() + # Scale
theme_classic()
# Population pyramid
population_german_states |>
filter(state %in% c("Berlin", "Mecklenburg-Vorpommern"), age < 90) |>
ggplot(aes(y = age, fill = sex, weight = n)) +
geom_bar_diverging(width = 1) +
geom_vline(xintercept = 0) +
scale_x_continuous_diverging(n.breaks = 10) +
facet_wrap(~state, scales = "free_x") +
theme_bw()
# Vaccination status: set neutral category
set.seed(456)
cases_vacc <- data.frame(year = 2017:2025) |>
rowwise() |>
mutate(vacc = list(sample(1:4, 100, prob = (4:1)^(1 - 0.2 * (year - 2017)), replace = TRUE))) |>
unnest(vacc) |>
mutate(
year = as.factor(year),
"Vaccination Status" = ordered(vacc,
labels = c("Fully Vaccinated", "Partially Vaccinated", "Unknown", "Unvaccinated")
)
)
ggplot(cases_vacc, aes(y = year, fill = `Vaccination Status`)) +
geom_vline(xintercept = 0) +
geom_bar_diverging(proportion = TRUE, neutral_cat = "force", break_pos = "Unknown") +
stat_diverging(
size = 3, proportion = TRUE, neutral_cat = "force", break_pos = "Unknown",
totals_by_direction = TRUE, nudge_label_outward = 0.05
) +
scale_x_continuous_diverging(labels = scales::label_percent(), n.breaks = 10) +
scale_y_discrete_reverse() +
ggtitle("Proportion of vaccinated cases by year") +
theme_classic() +
theme_mod_legend_bottom()
Run the code above in your browser using DataLab