How do I put labels above and below a vertical ggplot2 colour bar?

How can I place the labels at the two ends?

In ggplot2 4.0.4, use guide_custom() for end labels: this example keeps a linear 2–14 fill scale and draws a 64-band key.

On this page

Use a grid grob with text above and below the bar, then add it with guide_custom() and hide the automatic fill guide. I keep the labels inside the guide's own area, and the plot panel keeps its default clipping.

The original 3 by 4 heatmap has High (14) and Low (2) beside its colour bar.
Before: the automatic colour bar places both labels beside the bar. The twelve cell values total 91.
The same heatmap has High (14) above the bar and Low (2) below it.
After: High (14) sits above the dark end; Low (2) sits below the light end. All twelve tile coordinates and fill colours match the first plot. The guide changes the available panel space, so pixel positions can shift.

How do I keep the key consistent with the heatmap?

Sample the trained fill scale for the custom key. I use 64 equal score intervals between 2 and 14 and map their midpoints through the same scale that colours the tiles. The key is a banded approximation of that continuous scale; the cell annotations retain the exact numbers.

This is a fixed linear-scale example. A custom guide displays an independently supplied graphical object. Its labels, limits and direction require manual updates. If you change those choices, rebuild the key and check both endpoints. Log scales, reversed guides and out-of-range extensions need their own handling.

What code and files can I use?

Run the complete script below in an empty working folder with ggplot2 installed. It creates the data, two PNGs, a PDF and the checks. This article uses simulated example data.

The executed versions are R 4.5.3 and ggplot2 4.0.4. PNGs are 1200 × 900 pixels at 200 PPI; the PDF is 6 × 4.5 inches (432 × 324 points). The PDF references the standard Helvetica font.

The custom key is a 64 × 1 bitmap stretched to the guide area, including in the PDF. Using a single raster avoids visible seams between separate rectangles.

# Original Bopbun demonstration. CC0-1.0. Run in this file's directory.
library(ggplot2)
library(grid)

d <- expand.grid(column = 1:4, row = 1:3)
d$score <- c(2, 8, 4, 14, 6, 10, 12, 3, 9, 5, 11, 7)
write.csv(d, "synthetic.csv", row.names = FALSE)
limits <- c(2, 14)
fill_scale <- scale_fill_gradient(
  low = "#f1e5b6", high = "#264e70", limits = limits,
  breaks = limits, labels = c("Low (2)", "High (14)"), name = "Score"
)
p <- ggplot(d, aes(column, row, fill = score)) +
  geom_tile(colour = "white", linewidth = 1) +
  geom_text(aes(label = score, colour = ifelse(score >= 10, "white", "#18212b")),
            size = 4, fontface = "bold") + scale_colour_identity() +
  fill_scale + coord_fixed() +
  scale_x_continuous(breaks = 1:4) +
  scale_y_continuous(breaks = 1:3) +
  labs(x = "Column", y = "Row") + theme_minimal(base_size = 12) +
  theme(panel.grid = element_blank(), legend.position = "right")
before <- p + guides(fill = guide_colourbar(
  display = "rectangles", nbin = 64,
  theme = theme(legend.key.height = unit(34, "mm"))
))

# Use the trained fill scale so the guide and tiles share the same palette.
trained <- ggplot_build(p)$plot$scales$get_scales("fill")
n <- 64
edges <- seq(limits[1], limits[2], length.out = n + 1)
midpoints <- (head(edges, -1) + tail(edges, -1)) / 2
colours <- trained$map(midpoints)
key <- grobTree(
  rasterGrob(matrix(rev(colours), ncol = 1), x = 0.5, y = 0.5,
             width = 0.22, height = 0.64, interpolate = FALSE),
  textGrob("High (14)", x = 0.5, y = 0.93, gp = gpar(fontsize = 11)),
  textGrob("Low (2)", x = 0.5, y = 0.07, gp = gpar(fontsize = 11))
)
after <- p + guides(
  fill = "none",
  endpoint = guide_custom(key, width = unit(24, "mm"),
                          height = unit(52, "mm"), title = "Score")
)

for (nm in c("before", "after")) {
  png(paste0(nm, ".png"), width = 1200, height = 900, res = 200)
  print(get(nm)); dev.off()
}
pdf("after.pdf", width = 6, height = 4.5, timestamp = FALSE)
print(after); dev.off()
b <- ggplot_build(before)$data[[1]]
a <- ggplot_build(after)$data[[1]]
stopifnot(identical(b, a), sum(d$score) == 91,
          identical(as.character(key$children[[2]]$label), "High (14)"))
write.csv(data.frame(score = midpoints, fill = colours),
          "guide-samples.csv", row.names = FALSE)
write.csv(a, "tile-check.csv", row.names = FALSE)
writeLines(c("12 tile objects identical before/after; score sum=91",
             "64 custom guide bands; high above, low below",
             capture.output(sessionInfo())), "checks.txt")

These are the code, data and result files used in this article. Choose a file below to run the example or compare your results.

  • example.RComplete example code to run on your computer.
  • synthetic.csvThe input data used in the example; open it as a table.
  • guide-samples.csvThe sampled values and colors along the colorbar.
  • tile-check.csvHeatmap cell values before and after the colorbar change.
  • before.pngThe figure before the change, for comparison.
  • after.pngThe figure after applying the settings in this article.
  • after.pdfThe result in PDF format, for viewing and page layout.
  • Usage license · LICENSE.txtTerms for reusing the code, data and figures, with source and font notices.

Where can I check the guide behaviour?

The official guide_custom() documentation describes a guide that displays an independently supplied grob. guide_colourbar() documents the ordinary continuous guide. The R link below is a development manual; the executed R version is recorded above.

For saving a ggplot2 figure, see the separate export guide.

ggplot2 guide_custom · ggplot2 guide_colourbar · R grid