Fill cells with value = 0 with Red color

199 views Asked by At

I have a table:

table

and i need to fill cells with value = 0 with red color.

I realize i need data_color but how to set palette with 2 colors? red if value==0 , white if value<>0 ?

I've found an example:


    data_color(
  columns = colnames(updates.computers)[2:ncol(updates.computers)],
  colors = scales::col_numeric(
    palette = paletteer::paletteer_d(
               palette = "ggsci::red_material", direction = -1
             ) %>% as.character(),
             domain = NULL
           ),
           alpha = 0.8)

But it's not what I need.

example

I just need cells with 0 to be Red, and all the rest to stay White.

2

There are 2 answers

0
tamtam On BEST ANSWER

Have a look at the scales::col_bin function. By cutting the data into two bins (0 and from 1 to infinity) you can specify the colors for each bin.

df <- data.frame(A2020 = sample(0:10, 12, replace = TRUE),
                 B2020 = sample(0:10, 12, replace = TRUE),
                 C2020 = sample(0:10, 12, replace = TRUE),
                 D2020 = sample(0:10, 12, replace = TRUE),
                 E2020 = sample(0:10, 12, replace = TRUE),
                 F2020 = sample(0:10, 12, replace = TRUE),
                 G2020 = sample(0:10, 12, replace = TRUE),
                 H2020 = sample(0:10, 12, replace = TRUE),
                 I2020 = sample(0:10, 12, replace = TRUE),
                 J2020 = sample(0:10, 12, replace = TRUE))

gt(df) %>%
  data_color(
    columns = everything(),
    colors = scales::col_bin(
      bins = c(0, 1, Inf),
      palette = c("red", "white"),
    )
  )

enter image description here

0
Maxim On

Thanks, it works. The code:

    data_color(
    columns = colnames(updates.computers)[2:ncol(updates.computers)],
    colors = scales::col_bin(
      bins = c(0, 1, Inf),
      palette = c("red", "darkseagreen1"),
    ),
         alpha = 0.8
  )

The result: result