larmarange / ggstats

Extension to ggplot2 for plotting stats
https://larmarange.github.io/ggstats/
GNU General Public License v3.0
26 stars 1 forks source link

Feature request: Default inversed text colour based on fill background #57

Closed sda030 closed 4 months ago

sda030 commented 4 months ago

Having darker shades in the palette with black text is not the best. image

The code for inversing font colour is quite simple and fast:

hex_bw <- function(hex_code) {

  rgb_conv <-
    lapply(grDevices::col2rgb(hex_code), FUN = function(.x) {
      ifelse(.x / 255 <= 0.04045,
             .x * 12.92 / 255,
             ((.x / 255 + 0.055) / 1.055) ^ 2.4)
    }) %>%
    unlist() %>%
    matrix(ncol = length(hex_code), byrow = FALSE) %>%
    sweep(., MARGIN = 1, STATS = c(0.2126, 0.7152, 0.0722), FUN = `*`) %>%
    apply(., MARGIN = 2, FUN = sum)

  hex <- ifelse(rgb_conv > 0.179,
                "#000000",
                "#ffffff")

  hex[is.na(hex_code)] <- "#ffffff"
  hex

}
hex_bw("#123456")
sda030 commented 4 months ago

Which I would use with after_scale

geom_text(aes(colour = after_scale(x = hex_bw(.data$fill)))
larmarange commented 4 months ago

Thanks for the proposal. This is a good idea. I will look at it next week

larmarange commented 4 months ago

feature added. You can test the dev version

sda030 commented 4 months ago

Works well!