Search code examples
rdataframeformattable

How to change color gradient in formattable?


I am creating the following formattable: enter image description here

I have set the gradient on Var1 so that it gets increasingly red the higher the value is. I was wondering if it would be possible to change it so that it gets increasingly green the higher the value is. I love everything about it as it is, I just want the gradient to go from black to green rather than black to red. I have tried tweaking the numbers in the background-color command, but cannot seem to get it right. Is it possible to fix this? Is there a guide on numeric color gradients that perhaps I'm missing?

library(formattable)

ex <- structure(list(Group = 1:3, Var1 = c(0, 0.4, 0.8)), class = "data.frame", row.names = c(NA, 
-3L))

ex <- formattable(ex, 
                  align = c("l","l", "c", "c", "c", "c"),
                  list(Var1 = formatter("span",
                                                  style = x ~ style(display = "block",
                                                                    "border-radius" = "4px",
                                                                    "padding-right" = "4px",
                                                                    color = "white",
                                                                    "background-color" = rgb(ex$Var1/max(ex$Var1), 0, 0, 1)))))

Solution

  • You can define the gradient color with csscolor(gradient()). - That's also the functions used in the color_tile function of formattable.

    ex <- formattable(ex, 
                      align = c("l","l", "c", "c", "c", "c"),
                      list(Var1 = formatter("span",
                                            style = x ~ style(display = "block",
                                                              "border-radius" = "4px",
                                                              "padding-right" = "4px",
                                                              color = "white",
                                                              "background-color" = csscolor(gradient(as.numeric(x), "black", "green"))))))
    
    ex
    

    enter image description here