Intro to Heatmaps

Published

December 2, 2026

What is a heatmap?

A heatmap is a table drawn as a grid of colored tiles. Each row is one thing (a student, a country, a gene), each column is another (a class, a year, a condition), and the color of each tile shows the number in that cell. Darker tiles mean bigger numbers, so you can spot patterns at a glance without reading every value.

In this lesson we build a labeled heatmap one layer at a time with ggplot2. The finished plot shows how three students split their study time across four classes.

library(tidyverse)

The data

A small table with tribble()

tribble() lets you type a small tibble row by row, the way it looks on paper. Each row is a student, and each column is the number of hours they studied for a class last week.

study_wide <- tribble(
  ~student, ~Calculus, ~Biology, ~History, ~English,
  "Ana",           6,        2,        1,        1,
  "Ben",           1,        5,        3,        1,
  "Cal",           2,        2,        2,        2
)

study_wide
# A tibble: 3 × 5
  student Calculus Biology History English
  <chr>      <dbl>   <dbl>   <dbl>   <dbl>
1 Ana            6       2       1       1
2 Ben            1       5       3       1
3 Cal            2       2       2       2

Wide to long with pivot_longer()

This table is in wide format: one row per student, with the hours spread across four columns. ggplot needs long format, with one row per tile: a column for the row label (student), a column for the column label (class), and a column for the number (hours).

pivot_longer(-student, ...) stacks every column except student into two new columns: names_to holds the old column names, and values_to holds their values.

study <- study_wide |>
  pivot_longer(-student, names_to = "class", values_to = "hours")

study
# A tibble: 12 × 3
   student class    hours
   <chr>   <chr>    <dbl>
 1 Ana     Calculus     6
 2 Ana     Biology      2
 3 Ana     History      1
 4 Ana     English      1
 5 Ben     Calculus     1
 6 Ben     Biology      5
 7 Ben     History      3
 8 Ben     English      1
 9 Cal     Calculus     2
10 Cal     Biology      2
11 Cal     History      2
12 Cal     English      2

The 3 × 4 table became 12 rows, one for each tile in the heatmap.

Row percentages with group_by()

Raw hours are hard to compare when students study different amounts. Instead we show each class as a share of that student’s total.

group_by(student) makes sum(hours) add up only that student’s hours, so hours / sum(hours) is the share of their own time. ungroup() removes the grouping afterward, so it doesn’t affect later steps.

study <- study |>
  group_by(student) |>
  mutate(share = hours / sum(hours)) |>
  ungroup()

study
# A tibble: 12 × 4
   student class    hours share
   <chr>   <chr>    <dbl> <dbl>
 1 Ana     Calculus     6  0.6 
 2 Ana     Biology      2  0.2 
 3 Ana     History      1  0.1 
 4 Ana     English      1  0.1 
 5 Ben     Calculus     1  0.1 
 6 Ben     Biology      5  0.5 
 7 Ben     History      3  0.3 
 8 Ben     English      1  0.1 
 9 Cal     Calculus     2  0.25
10 Cal     Biology      2  0.25
11 Cal     History      2  0.25
12 Cal     English      2  0.25

Each student’s shares now add up to 1 (100%).

Building the heatmap

A first heatmap with geom_tile()

geom_tile() draws one rectangle at each x, y position, and fill = share colors it by the share. This is already a heatmap.

ggplot(study, aes(x = class, y = student)) +
  geom_tile(aes(fill = share))

It works, but there are things to fix:

  • The classes are in alphabetical order, not our table’s order.
  • Ana is at the bottom instead of the top.
  • The default color scale makes bigger numbers lighter, which is backward from what most readers expect.
  • You can’t read the exact values.

Choosing the order with factor()

ggplot sorts text alphabetically. To choose the order ourselves, we turn class and student into factors, whose levels set the order.

  • Classes go in the same order as the columns of study_wide: names(study_wide)[-1] is every column name except the first (student).
  • Students are reversed, because ggplot draws the first level at the bottom of the y axis, and we want Ana on top.
class_order <- names(study_wide)[-1]
student_order <- rev(study_wide$student)

study <- study |>
  mutate(
    class = factor(class, levels = class_order),
    student = factor(student, levels = student_order)
  )

ggplot(study, aes(x = class, y = student)) +
  geom_tile(aes(fill = share))

Better colors and tile borders

scale_fill_gradient() sets the colors at the two ends of the scale: white for 0, deep blue for the largest share. Now darker means more.

color = "white" with a thick linewidth draws white borders, which separate the tiles into a grid.

ggplot(study, aes(x = class, y = student)) +
  geom_tile(aes(fill = share), color = "white", linewidth = 2) +
  scale_fill_gradient(low = "white", high = "#3b5bdb")

Labels inside the tiles with geom_text()

geom_text() writes the value in each tile. scales::percent() turns 0.6 into “60%”, and accuracy = 1 rounds to whole percents.

ggplot(study, aes(x = class, y = student)) +
  geom_tile(aes(fill = share), color = "white", linewidth = 2) +
  geom_text(aes(label = scales::percent(share, accuracy = 1)), size = 7, fontface = "bold") +
  scale_fill_gradient(low = "white", high = "#3b5bdb")

The labels are now readable on light tiles, but dark text on the darkest tile is hard to read.

Readable labels on every tile

We give each label one of two colors depending on its tile: "light" (white) when the share is over 35%, and "dark" otherwise. Mapping color to that word inside aes() and then setting the actual colors with scale_color_manual() keeps the rule in one place.

Since the numbers are printed on the tiles, we don’t need the color legends either, so guide = "none" hides them.

ggplot(study, aes(x = class, y = student)) +
  geom_tile(aes(fill = share), color = "white", linewidth = 2) +
  geom_text(
    aes(
      label = scales::percent(share, accuracy = 1),
      color = if_else(share > 0.35, "light", "dark")
    ),
    size = 7,
    fontface = "bold"
  ) +
  scale_fill_gradient(low = "white", high = "#3b5bdb", limits = c(0, 0.6), guide = "none") +
  scale_color_manual(values = c(dark = "#222222", light = "white"), guide = "none")

limits = c(0, 0.6) fixes the ends of the color scale, so a share of 0 is pure white and 60% is the darkest blue.

Finishing touches

A summary next to each row

Percentages hide how much each student studied in total: Cal’s 25% is 2 hours, while Ana’s 20% for Biology is also 2 hours. Showing each student’s total hours next to their row fills in that context. We make a small table with one row per student, using the same factor order as the heatmap.

totals <- study |>
  group_by(student) |>
  summarize(total = sum(hours)) |>
  mutate(label = str_c(total, " hours total"))

totals
# A tibble: 3 × 3
  student total label         
  <fct>   <dbl> <chr>         
1 Cal         8 8 hours total 
2 Ben        10 10 hours total
3 Ana        10 10 hours total

Placing text outside the plot

The four columns sit at x = 1, 2, 3 and 4, so x = 4.6 is just to the right of the heatmap, and hjust = 0 left-aligns the text there. Two settings make room for it:

  • coord_cartesian(clip = "off") lets ggplot draw outside the plotting area.
  • plot.margin adds empty space on the right side of the figure (top, right, bottom, left, in points).

The finished heatmap

The last few changes make the plot read like a table:

  • scale_x_discrete(position = "top") moves the class names above the tiles.
  • expand = c(0, 0) removes the gap between the tiles and the axis labels.
  • theme_minimal() with panel.grid = element_blank() removes the grey background and grid lines.
  • plot.title.position = "plot" lines the title up with the left edge of the whole figure instead of the tiles.
  • labs(x = NULL, y = NULL) removes the axis titles, since the labels speak for themselves.
heatmap <- ggplot(study, aes(x = class, y = student)) +
  geom_tile(aes(fill = share), color = "white", linewidth = 2) +
  geom_text(
    aes(
      label = scales::percent(share, accuracy = 1),
      color = if_else(share > 0.35, "light", "dark")
    ),
    size = 7,
    fontface = "bold"
  ) +
  geom_text(
    data = totals,
    aes(x = 4.6, y = student, label = label),
    hjust = 0,
    size = 5,
    color = "#555555"
  ) +
  scale_fill_gradient(low = "white", high = "#3b5bdb", limits = c(0, 0.6), guide = "none") +
  scale_color_manual(values = c(dark = "#222222", light = "white"), guide = "none") +
  scale_x_discrete(position = "top", expand = c(0, 0)) +
  scale_y_discrete(expand = c(0, 0)) +
  coord_cartesian(clip = "off") +
  labs(
    title = "How each student split their study time",
    caption = "Each row adds up to 100%.",
    x = NULL,
    y = NULL
  ) +
  theme_minimal(base_size = 14) +
  theme(
    panel.grid = element_blank(),
    plot.title = element_text(face = "bold"),
    plot.title.position = "plot",
    plot.caption = element_text(color = "#777777", hjust = 0),
    plot.caption.position = "plot",
    plot.margin = margin(10, 150, 10, 10)
  )

heatmap

Saving the plot with ggsave()

ggsave() writes a plot to a file. width and height are in inches, dpi sets the resolution, and bg = "white" gives the image a white background instead of a transparent one.

ggsave("study_heatmap.png", heatmap, width = 9, height = 4, dpi = 200, bg = "white")

Try it yourself

  1. Add a fourth student to study_wide. What else in the code has to change? (Hint: look at student_order.)
  2. Change the heatmap to show raw hours instead of share. Which labels and limits need updating?
  3. Make the columns show each class’s share of all study time instead of each student’s. What do you group_by()?
  4. Try a different color with high =, or scale_fill_viridis_c(). Which is easiest to read?