Heatmap table using reactable in R

92 views Asked by At

I would like to color a table as a heatmap but I want to show the count in the table and color using the rate.

The table should show these numbers:

county <- c("Erie", "Orange", "Oneida")
jan <- c(8, 6, 5)
jul <- c(7, 3, 2)
dec <- c(17, 4, 6)
count_data <- data.frame(county, jan, jul, dec)

There colors should be based on:

county <- c("Erie", "Orange", "Oneida")
jan <- c(0.36, 0.27, 0.21)
jul <- c(0.7, 0.30, 0.17)
dec <- c(0.81, 0.18, 0.26)
rate_data <- data.frame(county, jan, jul, dec)

This is my code but something is not right:

my_color_pal = c('#e5f5e0', '#a1d99b', '#31a354', 'darkgreen')
#mypal = colorRampPalette(c("blue", "green", "yellow", "red"), bias = 0.5, space="Lab")

count_data |>   
  reactable(
    defaultColDef = colDef(
      style = color_scales(rate_data, span = 2:4, colors = my_color_pal)
    )
  ) |> 
  add_legend(
    data = rate_data,
    col_name = "dec",
    colors = my_color_pal,
    number_fmt = scales::percent_format(accuracy = 1L, scale = 1)
    # bin = 4
  )
1

There are 1 answers

0
itsMeInMiami On

Below is a reprex showing the issue. We want to shade the background of the dec column with the colors that are calculated in the dec_rate column. We never want to display the dec_rate column. We only want to use it to figure out how to shade the dec counts.

library(reactable)
library(reactablefmtr)

county <- c("Erie", "Orange", "Oneida")
dec <- c(17, 4, 6)
dec_rate <- c(0.81, 0.18, 0.91)
the_data <- data.frame(county, dec, dec_rate)

orange_pal <- function(x) rgb(colorRamp(c("#ffe4cc", "#ff9500"))(x), maxColorValue = 255)

reactable(
    the_data,
    columns = list(
        dec_rate = colDef(style = function(value) {
            normalized <- (value - min(the_data$dec_rate)) / (max(the_data$dec_rate) - min(the_data$dec_rate))
            color <- orange_pal(normalized)
            list(background = color)
        }),
        dec_rate = colDef("dec_rate")
    )
)

Created on 2023-10-18 with reprex v2.0.2

Is there a way to do this?