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

前端 未结 5 928
青春惊慌失措
青春惊慌失措 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条回答
  •  Happy的楠姐
    2020-12-12 01:58

    Based on @cmilando, I rewrite the function so that the colors reflect negative and positive numbers better, a bit manually though :D

    library(tidyverse)
    library(RColorBrewer)
    library(formattable)
    library(kableExtra)
    library(purrr)
    
    # --------------------
    # brewer.pal(10,"RdYlGn")
    
    my_color_tile <- function() {
      
      return_col <- function(y) 
        map_chr(y,function(x) case_when(x > 80  ~ "#006837",
                  x > 60  ~ "#1A9850",
                  x > 40  ~ "#66BD63",
                  x > 20  ~ "#A6D96A",
                  x >= 0  ~ "#D9EF8B",
                  x >= -20  ~ "#FEE08B",
                  x >= -40  ~ "#FDAE61",
                  x >= -60  ~ "#F46D43",
                  x >= -80  ~ "#D73027",
                  x >= -100  ~ "#A50026"
                  ))
      
      formatter("span", 
                style = function(y) style(
                  display = "block",
                  padding = "0 4px",
                  "border-radius" = "4px",
                  "color" = ifelse( return_col(y) %in% c("#A50026","#D73027","#F46D43","#006837","#1A9850","#66BD63"),
                                    csscolor("white"), csscolor("black")),
                  "background-color" = return_col(y)
                )
      )
    }
    
    # --------------------
    data.frame(value = c(seq(-100,100,10))) %>% 
      arrange(desc(value)) %>%  
      formattable(., list(
        area(col = 1) ~ my_color_tile()))
    
    

提交回复
热议问题