Grouped column chart with R

Cedric Vidonne

Lei Chen

Grouped column chart with R

Grouped column charts are a type of colour-coded column chart used to represent and compare different categories of two or more groups.

More about: Grouped column chart


Grouped 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_grouped.csv")

# Plot
ggplot(df) +
  geom_col(aes(
    x = year,
    y = refugee_number,
    fill = main_office
  ),
  position = position_dodge(width = 0.7),
  width = 0.6
  ) +
  scale_fill_unhcr_d(
    palette = "pal_unhcr",
    nmax = 3,
    order = c(2, 3, 1)
  ) +
  labs(
    title = "Refugees in Africa region | 2018-2021",
    y = "Number of people (in million)",
    caption = "Source: UNHCR Refugee Data Finder\n© UNHCR, The UN Refugee Agency"
  ) +
  scale_x_continuous(breaks = pretty_breaks(n = 4)) +
  scale_y_continuous(
    expand = expansion(c(0, 0.1)),
    labels = label_number_si()
  ) +
  theme_unhcr(
    grid = "Y",
    axis = "x",
    axis_title = "y"
  ) +
  guides(fill = guide_legend(nrow = 2, byrow = TRUE))
# Long legend labels so force in 2 rows

A grouped column chart showing refugee in Africa region | 2018-2021


Grouped 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_grouped.csv")

# Plot
ggplot(df) +
  geom_col(aes(
    x = year,
    y = refugee_number,
    fill = main_office
  ),
  position = position_dodge(width = 0.7),
  width = 0.6
  ) +
  geom_text(aes(
    x = year,
    y = refugee_number,
    group = main_office,
    label = round(refugee_number / 1e6, 1)
  ),
  position = position_dodge(width = 0.7),
  vjust = -1,
  size = 8 / .pt
  ) +
  scale_fill_unhcr_d(
    palette = "pal_unhcr",
    nmax = 3,
    order = c(2, 3, 1)
  ) +
  labs(
    title = "Refugees in Africa region | 2018-2021",
    subtitle = "Number of people (in million)",
    caption = "Source: UNHCR Refugee Data Finder\n© UNHCR, The UN Refugee Agency"
  ) +
  scale_x_continuous(breaks = pretty_breaks(n = 4)) +
  scale_y_continuous(expand = expansion(c(0, 0.1))) +
  theme_unhcr(
    grid = FALSE,
    axis = "x",
    axis_title = FALSE,
    axis_text = "x"
  ) +
  guides(fill = guide_legend(nrow = 2, byrow = TRUE))
# Long legend labels so force in 2 rows

A grouped column chart showing refugee in Africa region | 2018-2021


Related chart with R