Slope chart with R

Cedric Vidonne

Lei Chen

Slope chart with R

A slope chart looks like a line chart, but unlike the line chart, it has only two data points for each line. The change between two data points can be easily identified with connected lines (slope up means increase, slope down means decrease).

More about: Slope chart


Slope chart

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

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

# Plot
ggplot(df, aes(
  x = year,
  y = refugee_number,
  group = country_origin
)) +
  geom_line(
    size = 0.75,
    color = unhcr_pal(n = 1, "pal_blue")
  ) +
  geom_text_repel(
    data = df |> filter(year == 2016),
    aes(label = paste(
      country_origin,
      if_else(refugee_number > 1e6,
        paste0(round(refugee_number / 1e6, 1), "M"),
        paste0(round(refugee_number / 1e3, 1), "k")
      )
    )),
    size = 8 / .pt,
    hjust = 1,
    direction = "y",
    nudge_x = -0.3
  ) +
  geom_text_repel(
    data = df |> filter(year == 2021),
    aes(label = paste(
      country_origin,
      if_else(refugee_number > 1e6,
        paste0(round(refugee_number / 1e6, 1), "M"),
        paste0(round(refugee_number / 1e3, 1), "k")
      )
    )),
    size = 8 / .pt,
    hjust = 0,
    direction = "y",
    nudge_x = 0.3
  ) +
  geom_point(
    size = 2.5,
    color = unhcr_pal(n = 1, "pal_blue")
  ) +
  labs(
    title = "Evolution of refugee population in East and\nHorn of Africa region | 2016 vs 2021",
    caption = "Source: UNHCR Refugee Data Finder\n© UNHCR, The UN Refugee Agency"
  ) +
  scale_x_continuous(
    breaks = c(2016, 2021),
    limits = c(2013, 2024)
  ) +
  scale_y_continuous(limits = c(-2e5, NA)) +
  theme_unhcr(
    grid = "X",
    axis = FALSE,
    axis_title = FALSE,
    axis_text = "X"
  )

A slope chart showing evolution of refugee in East and Horn of Africa region | 2016 vs 2021


Related chart with R