Search code examples
rggplot2plotcolorslabel

Contrast between label and background: determine if color is light or dark


I have a barplot with labels in white. Sometimes the color of background is too light and the white label becomes illegible. I'm looking for a function that takes a color value and returns whether the color is dark or light. Then I can set the label color to white or black accordingly to obtain the best contrast against the background.


Solution

  • Here's a strategy to implement picking a text color of black vs white based on the intensity scale in the (second) link provided by @MrFlick.

    The blog cited a W3C publication: a standard formula for calculating the perceived brightness of a color that used an algorithm for RGB encoded colors:

     ((Red value X 299) + (Green value X 587) + (Blue value X 114)) / 1000
    

    The col2rgb function delivers a 3-row matrix which I multiply by the factors offered in that webpage. I used an example of "red" as a background color and the chosen text would then be "white"

     c( "black", "white")[  1+(sum( col2rgb("red") *c(299, 587,114))/1000 < 123) ]
    [1] "white"
    

    Implemented as a function:

    isDark <- function(colr) { (sum( col2rgb(colr) * c(299, 587,114))/1000 < 123) }
    isDark("red")
    [1] TRUE