Line chart with R

Cedric Vidonne

Lei Chen

Line chart with R

A line chart is a type of chart that displays the evolution of one or several numeric variables over a continuous interval or time period.

More about: Line chart


Single line 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/change_over_time/line.csv")

# Plot
ggplot(filter(df, population_type == "Refugees")) +
  geom_line(aes(
    x = year,
    y = population_number,
    group = population_type
  ),
  size = 1,
  color = unhcr_pal(n = 1, "pal_blue")
  ) +
  labs(
    title = "Number of refugees | 1991-2021",
    y = "Number of people",
    caption = "Source: UNHCR Refugee Data Finder\n© UNHCR, The UN Refugee Agency"
  ) +
  scale_x_continuous(breaks = pretty_breaks()) +
  scale_y_continuous(
    expand = expansion(c(0, 0.1)),
    breaks = pretty_breaks(n = 4),
    labels = label_number_si(),
    limits = c(5 * 1e6, 25 * 1e6)
  ) +
  theme_unhcr(
    grid = "Y",
    axis = "x",
    axis_title = "y"
  )

A line chart showing number of refugees | 1990-2021


Multiple lines chart

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

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

# Plot
ggplot(df, aes(
  x = year,
  y = population_number,
  color = population_type
)) +
  geom_line(size = 1) +
  geom_dl(aes(label = population_type),
    method = list(
      dl.trans(x = x + 0.1),
      "last.points"
    ),
    size = 8 / .pt
  ) +
  labs(
    title = "Number of refugees and IDPs of concern to UNHCR | 1991-2021",
    y = "Number of people",
    caption = "Source: UNHCR Refugee Data Finder\n© UNHCR, The UN Refugee Agency"
  ) +
  scale_x_continuous(breaks = pretty_breaks()) +
  scale_y_continuous(
    expand = expansion(c(0, 0.1)),
    breaks = pretty_breaks(),
    labels = label_number_si(),
    limits = c(0, 60 * 1e6)
  ) +
  scale_color_unhcr_d(
    palette = "pal_unhcr",
    nmax = 10,
    order = c(5, 1)
  ) +
  coord_cartesian(clip = "off") +
  theme_unhcr(
    grid = "Y",
    axis = "x",
    axis_title = "y",
    legend = FALSE
  ) +
  theme(plot.margin = margin(r = 50))

A line chart showing number of refugees and IDPs of concern to UNHCR | 1990-2021


Related chart with R