Is it possible to use more than 2 colors in the color_tile function?

前端 未结 5 930
青春惊慌失措
青春惊慌失措 2020-12-12 01:29

I have a dataframe column that I\'m currently formatting using the formattable::color_tile function (below):

color_tile( \"red\", \"springgreen\"

5条回答
  •  天命终不由人
    2020-12-12 01:57

    Something like this might work, leveraging RColorBrewer

    color_tile3 <- function(fun = "comma", digits = 0, palette = 'RdBu', n = 9) {
      fun <- match.fun(fun)
    
      stopifnot(n >= 5)
      
      return_cut <- function(y) 
        cut(y, breaks = quantile(y, probs = 0:n/n, na.rm = T),
            labels = 1:n, ordered_result = T, include.lowest = T)
      
      return_col <- function(y) 
          RColorBrewer::brewer.pal(n, palette)[as.integer(return_cut(y))]
      
      formatter("span", x ~ fun(x, digits = digits),
                style = function(y) style(
                  display = "block",
                  padding = "0 4px",
                  "border-radius" = "4px",
                  "color" = ifelse( return_cut(y) %in% c(1, 2, n-1, n),
                                    csscolor("white"), csscolor("black")),
                  "background-color" = return_col(y)
                )
      )
    }
    

    Use case:

    library(tidyverse)
    library(RColorBrewer)
    
    mtcars[, 1:5] %>%
      corrr::correlate() %>%
      formattable(., list(
        `rowname` = formatter("span", style = ~ style(color = "grey", 
                                                      font.weight = "bold")), 
        area(col = 2:6) ~ color_tile3(digits = 2)))
    

    mtcars_color3

    I can't embed yet, but here's a link to the output

提交回复
热议问题