Stacked bar chart with R
Stacked bar charts stack horizontal bars that represent different groups one after another. The length of the stacked bar shows the combined value of the groups.
More about: Stacked bar chart
Stacked bar chart
# Loading required packages
library(unhcrthemes)
library(tidyverse)
library(scales)
# Loading data
<- read_csv("https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/comparison/bar_stacked.csv")
df
# Plot
ggplot(df) +
geom_col(aes(x = population_number,
y = reorder(country_origin, population_number),
fill = population_type),
width = 0.7) +
labs(title = "People displaced across borders by country of origin | 2021",
x = "Number of people",
caption = "Source: UNHCR Refugee Data Finder\n© UNHCR, The UN Refugee Agency") +
scale_x_continuous(expand = expansion(c(0, 0.1)),
breaks = pretty_breaks(n = 7),
labels = label_number_si()) +
scale_fill_unhcr_d(palette = "pal_unhcr",
nmax = 10,
order = c(3, 1, 9),
labels = c("Asylum-seekers", "Refugees", "Venezuelans displaced abroad")) +
theme_unhcr(grid = "X",
axis = "y",
axis_title = "x")
Stacked bar chart with labels
# Loading required packages
library(unhcrthemes)
library(tidyverse)
library(scales)
# Loading data
<- read_csv("https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/comparison/bar_stacked.csv")
df
# Plot
ggplot(df) +
geom_col(aes(x = population_number,
y = reorder(country_origin, population_number),
fill = population_type),
width = 0.7) +
geom_text(data = filter(df, population_number > 180000),
aes(x = population_number,
y = reorder(country_origin, population_number),
group = population_type,
label = round(population_number / 1e6, 1)),
position = position_stack(vjust = 0.5),
size = 8/.pt,
color = "#FFFFFF") +
labs(title = "People displaced across borders by country of origin | 2021",
subtitle = "Number of people (million)",
caption = "Source: UNHCR Refugee Data Finder\n© UNHCR, The UN Refugee Agency") +
scale_x_continuous(expand = expansion(c(0, 0.1))) +
scale_fill_unhcr_d(palette = "pal_unhcr",
nmax = 10,
order = c(3, 1, 9),
labels = c("Asylum-seekers", "Refugees", "Venezuelans displaced abroad")) +
theme_unhcr(fgrid = FALSE,
axis = "y",
axis_title = FALSE,
axis_text = "y")