Create diverging color scheme for gt_color_box from GT package

36 Views Asked by At

I would like to modify the palette of the gt_color_box() function from the R package GT such that It can accommodate two scales:

  1. Numbers below and equal to zero (color1, color2)
  2. Numbers above 0 (color3, color 4)

Similar to this scale except negatives will have the purple scale and positives will have the green scale

The code for the function is below and I'm unclear on how to modify it. Any help would be greatly appreciated.

gt_color_box <- function(gt_object, columns, palette = NULL, ..., domain = NULL,
                         width = 70, font_weight = "bold") {
  stopifnot("Table must be of class 'gt_tbl'" = "gt_tbl" %in% class(gt_object))

  color_boxes <- function(x) {
    stopifnot("Error: 'domain' must be specified." = !is.null(domain))

    if (length(palette) == 1) {
      if (grepl(x = palette, pattern = "::", fixed = TRUE)) {
        palette <- paletteer::paletteer_d(
          palette = palette
        ) %>% as.character()
      } else {
        palette <- palette
      }
    } else if (is.null(palette)) {
      palette <- c(
        "#762a83", "#af8dc3", "#e7d4e8", "#f7f7f7",
        "#d9f0d3", "#7fbf7b", "#1b7837"
      )
    } else {
      palette <- palette
    }

    if (palette[1] == "pff") palette <- c("#cd2624", "#fd9701", "#ffd000", "#3bae24", "#0c5ea0")

    colors <- scales::col_numeric(palette = palette, domain = domain)(x)

    background_col <- scales::alpha(colors, alpha = 0.2)

    div(
      div(
        style = paste0(
          glue::glue(
            "height: 20px;width:{width}px; background-color: {background_col};"
          ),
          "border-radius:5px;)"
        ),
        div(
          style = paste0(
            glue::glue("height: 13px;width: 13px;background-color: {colors};"),
            "display: inline-block;border-radius:4px;float:left;",
            "position:relative;top:17%;left:6%;" # top 12%-15%
          )
        ),
        div(
          scales::label_number(...)(x),
          style = paste0(
            glue::glue("display: inline-block;float:right;line-height:20px; font-weight: {font_weight};"),
            "padding: 0px 2.5px;"
          )
        )
      )
    ) %>%
      as.character() %>%
      html()
  }

  text_transform(
    gt_object,
    locations = cells_body({{ columns }}),
    fn = function(x) {
      x <- as.double(x)
      lapply(x, color_boxes)
    }
  )
}

0

There are 0 best solutions below