Skip to content

Add col_contrasting()#521

Open
arcresu wants to merge 1 commit into
r-lib:mainfrom
arcresu:col_contrasting
Open

Add col_contrasting()#521
arcresu wants to merge 1 commit into
r-lib:mainfrom
arcresu:col_contrasting

Conversation

@arcresu
Copy link
Copy Markdown

@arcresu arcresu commented Apr 3, 2026

This function is very useful for picking an appropriate text colour based on the background colour, especially inside after_scale(). The intended usage is this:

library(ggplot2)
library(dplyr)

expand.grid(x = 1:5, y = 1:5) |>
  mutate(n = row_number()) |>
  ggplot(aes(x, y, fill = n)) +
  geom_tile()+
  geom_text(aes(
    label = n,
    colour = after_scale(col_contrasting(fill))
  ))
image

There are many versions of this function floating around on the internet, many using a lot of heuristics to find the threshold for light/dark. I went with using the midpoint of lightness in Lab space. Of course this could be made configurable, and it doesn't necessarily have to live alongside the colour manipulation family. I do think it's worth having something like this in scales though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant