Grouped bar chart with R

Cedric Vidonne

Lei Chen

Grouped bar chart with R

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

More about: Grouped bar chart


Grouped bar 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/bar_grouped.csv")

# Plot
ggplot(df) +
  geom_col(aes(
    x = asylum_application,
    y = fct_rev(factor(region)),
    fill = as.character(year)
  ),
  position = position_dodge(0.7),
  width = 0.6
  ) +
  scale_fill_unhcr_d(palette = "pal_unhcr") +
  labs(
    title = "Individual asylum applications registered by region | 2019-2020",
    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)),
    labels = label_number_si()
  ) +
  scale_y_discrete(labels = scales::label_wrap(17)) +
  theme_unhcr(
    grid = "X",
    axis = "y",
    axis_title = "x"
  )

A grouped bar chart showing individual asylum applications registered by region | 2019-2020


Grouped bar 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/bar_grouped.csv")

# Plot
ggplot(df) +
  geom_col(aes(
    x = asylum_application,
    y = fct_rev(factor(region)),
    fill = as.character(year)
  ),
  position = position_dodge(width = 0.7),
  width = 0.6
  ) +
  geom_text(aes(
    x = asylum_application,
    y = fct_rev(factor(region)),
    group = as.character(year),
    label = round(asylum_application / 1e3)
  ),
  position = position_dodge(width = 0.7),
  hjust = -0.25, size = 8 / .pt
  ) +
  scale_fill_unhcr_d(palette = "pal_unhcr") +
  labs(
    title = "Individual asylum applications registered by region | 2019-2020",
    subtitle = "Number of people (thousand)",
    caption = "Source: UNHCR Refugee Data Finder\n© UNHCR, The UN Refugee Agency"
  ) +
  scale_x_continuous(expand = expansion(c(0, 0.1))) +
  scale_y_discrete(labels = scales::label_wrap(17)) +
  theme_unhcr(
    grid = FALSE,
    axis = "y",
    axis_title = FALSE,
    axis_text = "y"
  )

A grouped bar chart showing individual asylum applications registered by region | 2019-2020


Related chart with R