Search code examples
rggplot2color-palettegt

Imitate Excel style gradient color effect (red, yellow, green) in gt::data_color()


With code and sample data below, I plot a gt table:

df <- structure(list(date = c("2016-1-31", "2016-2-29", "2016-3-31", 
"2016-4-30", "2016-5-31", "2016-6-30", "2016-7-31", "2016-8-31", 
"2016-9-30"), value1 = c(-15.25, -27.96, 7.53, -5.24, -6.93, 
-6.83, -6.47, 13, -10.48), value2 = c(-19.93, -13.76, 20, -11.12, 
-0.59, -9.06, 15, 1.66, -1.59)), class = "data.frame", row.names = c(NA, 
-9L))

library(gt)
library(tidyverse)

df %>% 
  gt() %>% 
  data_color(
    columns = value1:value2,
    colors = scales::col_numeric(
      palette = c(
        'red', 'yellow', 'green'),
      domain = c(df$value1, df$value2))
  )

enter image description here

Next step I attempted to achieve an approximately same color effect as the following plot, which I have done by the simply selecting the default 3-color scale: red, yellow, green from the Format Style drop-down list in Excel.

enter image description here

Does someone knows the values of the following hex color codes or other R's color palette could achieve same effect? Thanks.

enter image description here

Update: I obtain the similar color codes: "#f8696b", "#ffeb84", "#63be7b"

df %>% 
  gt() %>% 
  data_color(
    columns = value1:value2,
    colors = scales::col_numeric(
      palette = c(
        "#f8696b", "#ffeb84", "#63be7b"),
      domain = c(df$value1, df$value2))
  )

enter image description here

References:

https://www.excel-easy.com/examples/color-scales.html

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?


Solution

  • The similar color palette: c("#63be7b", "#ffeb84", "#f8696b")

    df %>% 
      gt() %>% 
      data_color(
        columns = value1:value2,
        colors = scales::col_numeric(
          palette = c(
            "#63be7b", "#ffeb84", "#f8696b"),
          domain = c(df$value1, df$value2))
      )
    

    Out:

    enter image description here