Search code examples
rgt

How to bin values into positive and negative using the R package scales


I'm trying to use the package gt (here) to build a table. gt uses color mapping functions from the scales package to fill table cells based on values. I'm trying to just get negative values filled red and non-negative filled green. A simple example

library(magrittr)
library(gt)

column_one <- c("Larry", "Moe", "Curly", "Bob")
column_two <- c(-500, 30000, 0, 100)

dframe <- data.frame(column_one, column_two, stringsAsFactors = FALSE)

names(dframe)[1] <- "Name"
names(dframe)[2] <- "Change"

dframe %>% gt() %>%
  data_color(
    columns=vars(Change),
    colors = scales::col_bin(
      palette = c("red", "green"),
      bins=2,
      domain = NULL
    )
  )

produces this table

enter image description here

I don't want the interpolated mustardy yellow...just red or green.

From the gt documentation

The color mapping functions are: scales::col_quantile(), scales::col_bin(), scales::col_numeric(), and scales::col_factor()

Any help on how to achieve this would be greatly appreciated.


Solution

  • You can use bins to specify the cut-points you want to break the data in. Try :

    library(magrittr)
    library(gt)
    
    dframe %>% gt() %>%
      data_color(
        columns = vars(Change),
        colors = scales::col_bin(
          bins = c(-Inf, 0, Inf),
          palette = c("red", "green"),
        )
      )
    

    enter image description here