Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

color_tile( "red", "springgreen" )

My issue with this is that the values near the middle are an ugly brown color, and I'd ideally like it to be a red-amber-green gradient, but color_tile seems to only be able to take min.color and max.color parameters - is it possible to use a 3rd color with either this or similar formatting functions in R?

like image 853
henrygd Avatar asked Nov 02 '25 13:11

henrygd


2 Answers

It doesn't look like the function is designed to handle more than two colors, but you can make your own building on that template.

color_tile2 <- function (...) {
  formatter("span", style = function(x) {
    style(display = "block",
          padding = "0 4px", 
          `border-radius` = "4px", 
          `background-color` = csscolor(matrix(as.integer(colorRamp(...)(normalize(as.numeric(x)))), 
                                               byrow=TRUE, dimnames=list(c("red","green","blue"), NULL), nrow=3)))
  })}

which can be used like

formattable(mtcars, list(mpg = color_tile2(c("white", "pink"))))
formattable(mtcars, list(mpg = color_tile2(c("blue", "green", "pink"))))
like image 62
MrFlick Avatar answered Nov 04 '25 04:11

MrFlick


Determine which row numbers you want between color 1 and 2 and which row numbers for between color 2 and 3. Then call color_tile twice. For example

formattable(x, 
        list(
          area(col = 2, row = c(1,3,5,7,8,9,10,13,14,15)) ~ color_tile("red", "white"),
          area(col = 2, row = c(2,4,6,11,12,16)) ~ color_tile("white","green")
        ))

Won't fix it perfectly, since it won't keep the relative intensity of the colors on either side

like image 20
Yoni Schoenberg Avatar answered Nov 04 '25 05:11

Yoni Schoenberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!