Bar chart with R

Cedric Vidonne

Lei Chen

Bar chart with R

A bar chart is a chart in which each category is represented by a horizontal rectangle, with the length of the rectangle proportional to the values being plotted.

More about: Bar chart


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

# Plot
ggplot(df) +
  geom_col(aes(
    x = displaced_number,
    y = reorder(country_origin, displaced_number)
  ),
  fill = unhcr_pal(n = 1, "pal_blue"),
  width = 0.8
  ) +
  labs(
    title = "People displaced across borders by country of origin | 2021",
    x = "Number of people (in million)",
    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()
  ) +
  theme_unhcr(
    grid = "X",
    axis = "y",
    axis_title = "x"
  )

A bar chart showing people displaced across borders by country of origin | 2020


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

# Plot
ggplot(df) +
  geom_col(aes(
    x = displaced_number,
    y = reorder(country_origin, displaced_number)
  ),
  fill = unhcr_pal(n = 1, "pal_blue"),
  width = 0.8
  ) +
  geom_text(aes(
    x = displaced_number,
    y = reorder(country_origin, displaced_number),
    label = round(displaced_number / 1e6, 2)
  ),
  hjust = -0.5,
  size = 8 / .pt
  ) +
  labs(
    title = "People displaced across borders by country of origin | 2021",
    subtitle = "Number of people (in million)",
    caption = "Source: UNHCR Refugee Data Finder\n© UNHCR, The UN Refugee Agency"
  ) +
  scale_x_continuous(expand = expansion(c(0, 0.1))) +
  theme_unhcr(
    grid = FALSE,
    axis = "y",
    axis_title = FALSE,
    axis_text = "y"
  )

A bar chart showing people displaced across borders by country of origin | 2020


Related chart with R