Stacked column chart with R

Cedric Vidonne

Lei Chen

Stacked column chart with R

The stacked column chart stacks vertical bars that represent different groups on top of each other. The height of the stacked bar shows the combined value of the groups.

More about: Stacked column chart


Stacked column chart

# Loading required packages
library(unhcrthemes)
library(tidyverse)
library(scales)

# Loading data
df <- read_csv("https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/comparison/column_stacked.csv")

# Plot
ggplot(df) +
  geom_col(aes(x = year,
               y = rst_in_thousand,
               fill = rst_type),
           width = 0.7) +
  scale_fill_unhcr_d(palette = "pal_unhcr",
                     nmax = 2,
                     order = 2:1) +
  scale_x_continuous(breaks = pretty_breaks(n = 11)) +
  scale_y_continuous(expand = expansion(c(0, 0.2))) +
  labs(title = "Resettlement by UNHCR and others | 2010-2020",
       y = "Number of people (thousand)",
       caption = "Source: data source here\n© UNHCR, The UN Refugee Agency") +
  theme_unhcr(grid = "Y",
              axis = "x",
              axis_title = "y")

A stacked column chart showing resettlement by UNHCR and others | 2010-2020


Stacked column chart with labels

# Loading required packages
library(unhcrthemes)
library(tidyverse)
library(scales)

# Loading data
df <- read_csv("https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/comparison/column_stacked.csv")

# Plot
ggplot(df) +
  geom_col(aes(x = year,
               y = rst_in_thousand,
               fill = rst_type),
           width = 0.7) +
  geom_text(aes(x = year,
                y = rst_in_thousand,
                color = rst_type,
                label = rst_in_thousand),
            position = position_stack(vjust = 0.5),
            show.legend = FALSE,
            size = 8/.pt) +
  scale_color_manual(values = c("#000000", "#FFFFFF")) +
  scale_fill_unhcr_d(palette = "pal_unhcr",
                     nmax = 2,
                     order = 2:1) +
  scale_x_continuous(breaks = pretty_breaks(n = 11)) +
  scale_y_continuous(expand = expansion(c(0, 0.1))) +
  labs(title = "Resettlement by UNHCR and others | 2010-2020",
       subtitle = "Number of people (thousand)",
       caption = "Source: data source here\n© UNHCR, The UN Refugee Agency") +
  theme_unhcr(grid = FALSE,
              axis = "x",
              axis_title = FALSE,
              axis_text = "x")

A stacked column chart showing resettlement by UNHCR and others | 2010-2020


Related chart with R