Heatmap with R

Cedric Vidonne

Lei Chen

Heatmap with R

A heatmap is a type of visualization that values are depicted through variations in colour within a two-dimensional matrix of cells. It allows us to visualize complex data and understand it at a glance.

More about: Heatmap


Heatmap

# 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/correlation/heatmap.csv")

# Plot
ggplot(
  df,
  aes(
    x = year,
    y = fct_rev(location)
  )
) +
  geom_tile(aes(
    fill = values
  ),
  color = "white",
  lwd = .5,
  linetype = 1
  ) +
  labs(
    title = "Refugee population by region | 2011 - 2020",
    caption = "Source: UNHCR Refugee Data Finder\n© UNHCR, The UN Refugee Agency"
  ) +
  scale_x_continuous(
    expand = expansion(c(0, 0)),
    breaks = pretty_breaks(n = 10)
  ) +
  scale_y_discrete(
    labels = scales::label_wrap(17)
  ) +
  scale_fill_stepsn(
    colors = unhcr_pal(n = 5, "pal_blue"),
    n.break = 5,
    name = "Number of people\nin millions"
  ) +
  coord_fixed() +
  theme_unhcr(
    font_size = 13,
    grid = FALSE,
    axis = FALSE,
    axis_title = FALSE,
    legend_title = TRUE
  )

A heatmap showing refugee population by region | 2011-2020


Heatmap 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/correlation/heatmap.csv")

# Plot
ggplot(
  df,
  aes(
    x = year,
    y = fct_rev(location)
  )
) +
  geom_tile(aes(
    fill = values
  ),
  color = "white",
  lwd = .5,
  linetype = 1
  ) +
  geom_text(
    aes(
      label = scales::number(values, accuracy = 0.1)
    ),
    color = if_else(df$values > 2, "white", unhcr_pal(n = 5, "pal_grey")[5]),
    size = 8 / .pt
  ) +
  labs(
    title = "Refugee population by region | 2011 - 2020",
    subtitle = "Number of people in millions",
    caption = "Source: UNHCR Refugee Data Finder\n© UNHCR, The UN Refugee Agency"
  ) +
  scale_x_continuous(
    expand = expansion(c(0, 0)),
    breaks = pretty_breaks(n = 10)
  ) +
  scale_y_discrete(
    labels = scales::label_wrap(17)
  ) +
  scale_fill_stepsn(
    colors = unhcr_pal(n = 5, "pal_blue"),
    n.break = 5
  ) +
  coord_fixed() +
  theme_unhcr(
    grid = FALSE,
    axis = FALSE,
    axis_title = FALSE,
    legend = FALSE
  )

A heatmap showing refugee population by region | 2011-2020


Related chart with R