Skip to content

Instantly share code, notes, and snippets.

@realmiketalbot
Created January 21, 2026 19:59
Show Gist options
  • Select an option

  • Save realmiketalbot/0bd0af38c5b0f74c0d1fe16f895fe80d to your computer and use it in GitHub Desktop.

Select an option

Save realmiketalbot/0bd0af38c5b0f74c0d1fe16f895fe80d to your computer and use it in GitHub Desktop.
Replicate matplotlib's `plt.colorbar` with `extend` using ggplot2
# Took me a while to figure this out, so I thought I'd archive and share
# Here's a reprex:
library(ggplot2)
library(scales)
library(legendry)
# Built-in data
df <- mtcars
# Force some values outside the limits so the end-caps are meaningful
df$drat2 <- df$drat
df$drat2[c(1, 2)] <- df$drat2[c(1, 2)] + 0.9 # above max
df$drat2[c(3, 4)] <- df$drat2[c(3, 4)] - 0.9 # below min
p <- ggplot(df, aes(mpg, wt, colour = drat2)) +
geom_point(size = 2) +
scale_colour_viridis_c(
limits = c(3, 4),
oob = scales::oob_squish, # clamp out-of-bounds values to limits
guide = legendry::guide_colbar(
shape = "triangle", # triangle end-caps
show = TRUE # show caps on both ends (like extend="both")
# try show = NA to show caps only when needed
)
) +
labs(
title = "ggplot2 colourbar with triangle end-caps (matplotlib-like extend='both')",
colour = "drat2"
) +
theme_minimal(base_size = 12)
print(p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment