Create a Heatmap in R ggplot2 to Visualize African Population Distribution

Bo Yuan, Ph.D.
2 min readMay 7, 2024
Heatmap created in R ggplot2. Image by Author.

Heatmaps are powerful tools in data visualization, and the famous ggplot2 package provides the needed tools to create such stunning visuals in an easy and creative way. The above heatmap created with ggplot2 is such an excellent demonstration, with code displayed below; a stepwise instruction and illustration for this work can be found here. The dataset used in this visualization comes from the awesome afrilearndata package, and the code is inspired by and adapted from the work of Georgios Karamanis.

library(ggplot2)
library(dplyr)

# the African population dataset
# install.packages("remotes") # if not already installed
# remotes::install_github("afrimapr/afrilearndata") # if fails, try restarting R
library(afrilearndata)

# packages for data cleanup
library(raster)
library(sp)

# Load "Paytone One" font from Google Fonts Repository.
library(showtext)
font_add_google(name = "Paytone One", family = "Paytone One")
showtext.auto() # use 'showtext' to draw text

# Data cleanup
afripop_df <- afripop2020 %>%
as.data.frame(xy = TRUE) %>%
rename(pop = 3) %>%
filter(!is.na(pop)) %>%
as_tibble()

afripop_df %>%
# Create a heatmap base.
ggplot() +
geom_raster(aes(x, y, fill = pop)) +
coord_fixed(ratio = 1.1) +

# Adjust color scale
scale_fill_viridis_c(trans = "pseudo_log", option = "G",
breaks = c(0, 100, 1000, 5000, 20000),
labels = function(x) {paste(x/1000, "K")} ) +

# adjust legend. Use unicode for easy input of superscripts.
theme_void() +
theme(legend.position = "bottom") +

# further customize the colorbar legend
guides(fill = guide_colorbar(
barwidth = unit(200, "pt"),
barheight = unit(5, "pt"),
title.position = "top",
title = "populatin density / km²",
title.theme = element_text(hjust = .5, family = "Paytone One"))) +

# Add plot title.
annotate(geom = "text", x = -20, y = -10, label = "Africa",
size = 11, family = "Paytone One", hjust = 0) +

# Add a warm background as a final touch.
theme(plot.background = element_rect(fill = "cornsilk", color = NA),
# increase the margin around the plot
plot.margin = margin(b = 20, l = 10, r = 10, t = 10))

# Save the plot.
ggsave("Heatmap of African population.pdf",
path = "graphics",
device = "pdf",
width = 4.2, height = 5.6)

If you want to develop a systematic working knowledge in R ggplot2, I encourage you to check out my unique ggplot2 eBook. Designed in a line-by-line and plot-by-plot format on each page, it promises to take you to a rewarding and engaging learning journey like flipping through a comic book. You’ll be just amazed at how fast you can use your learning from my eBook to address real-world visualization tasks with confidence and creativity!

--

--

Bo Yuan, Ph.D.

Postdoctoral Fellow at Harvard University | Analytical chemist | Physiologist | Data scientist | Co-founder of DataBrewer.co.