R 中的日历热图

问题描述

希望在 R 中创建一个 gt/reactable 表,用作日历热图。就像在本网站 https://glin.github.io/reactable/articles/cookbook/cookbook.html 上找到的一样。当我尝试复制该代码时,出现错误:“仅在具有所有类似数字的变量的数据框中定义。”我将 Year 设为因子变量,不想为该列着色。这是我尝试过的代码 + dput 输出

BuYlRd <- function(x) rgb(colorRamp(c("#7fb7d7","#ffffbf","#fc8d59")) 
(x),maxColorValue = 255)

reactable(
  bls,defaultColDef = colDef(
    style = function(value) {
      if (!is.numeric(value)) return()
      normalized <- (value - min(bls)) / (max(bls) - min(bls))
      color <- BuYlRd(normalized)
      list(background = color)
    },format = colFormat(digits = 2),minWidth = 50
  ),columns = list(
    .rownames = colDef(name = "Year",sortable = TRUE,align = 
"left")
  ),bordered = TRUE
)

dput(head(bls))

 structure(list(year = structure(1:3,.Label = c("2018","2019","2020"),class = "factor"),January = c(329.5,329.6,327.5),February = c(354.4,328.5,323.7),march = c(354.4,324,324.9),April = c(348.7,326.9,319.8),May = c(340.2,321,320.7),June = c(338,316.1,320.4),July = c(342.3,317.3,319),August = c(346.8,317.2),September = c(344.9,317),October = c(342.4,318.2,317.3),November = 
    c(334.4,328.2),December = c(335.5,317.4,328.7)),row.names = 
    c(NA,-3L),class = c("tbl_df","tbl","data.frame"))

解决方法

解决方案可能是将年份列放入数据集的行名中,然后删除年份列:

bls=as.data.frame(bls)
rownames(bls)=bls$year
bls=bls[,-1]
reactable(
  bls,defaultColDef = colDef(
    style = function(value) {
      if (!is.numeric(value)) return()
      normalized <- (value - min(bls)) / (max(bls) - min(bls))
      color <- BuYlRd(normalized)
      list(background = color)
    },format = colFormat(digits = 2),minWidth = 50
  ),columns = list(
    .rownames = colDef(name = "Year",sortable = TRUE,align = 
"left")
  ),bordered = TRUE
)

enter image description here