【问题标题】:Huxtable: color code a matrix by another matrixHuxtable:用另一个矩阵对一个矩阵进行颜色编码
【发布时间】:2019-11-29 23:51:31
【问题描述】:

是否可以通过不同的表格中给出的颜色对表格(使用 huxtable 生成)进行颜色编码?

head_mtcars <- head(mtcars)
tbl_A <- as_hux(head_mtcars[1:2])
tbl_B <- as_hux(head_mtcars[3:4])

1) 首先,我想分别为tbl_A 的第 1 列和第 2 列中的元素着色,分别为每一列的颜色空间

tbl_A %>% 
  huxtable::add_colnames() %>% 
  map_background_color("for each column of tbl_A", by_colorspace("orange", "white", "green"))

2) 接下来,我想为tbl_A 的第 1 列和第 2 列中的元素通过 tbl_B 的每一列的颜色空间着色, 即tbl_B[,1]tbl_A 的col 1 中的元素和tbl_B[,2]tbl_A 的col 2 中的元素

tbl_A %>% 
huxtable::add_colnames() %>% 
  map_background_color("for each column of tbl_B", by_colorspace("orange", "white", "green"))

3) 最后,不是按列,而是按整个表格:根据 ht2 的值对 ht 中的元素着色:

ht <- as_hux(matrix(rnorm(25), 5, 5))
ht2 <- as_hux(matrix(rnorm(25), 5, 5))
map_background_color(ht, by_colorspace("orange", "white", "green"))

非常感谢您的帮助!

【问题讨论】:

标签: r


【解决方案1】:

A 部分:要按列应用颜色空间,您必须单独指定它们:

tbl_A %>% 
  map_background_color(everywhere, 1, by_colorspace("orange", "white", "green")) %>%
  map_background_color(everywhere, 2, by_colorspace("orange", "white", "green")) %>%
  huxtable::add_colnames() 

这可能是一个功能请求,因为我可以想象按列执行它是一个常见的用例。

B 部分:我认为“手动”执行此操作将是最简单的 - 即构建您想要的颜色,然后在 set_background_color 中使用它们。我们可以在map_ 调用之外使用huxtable 的by_colorspace,就像这样。同样,按列分别完成:

# this is hairy. Details in ?"huxtable::mapping-functions"
colors1 <- by_colorspace("orange", "white", "green")(tbl_B, 1:6, 1, 
      matrix(NA, 6, 1))
colors2 <- by_colorspace("orange", "white", "green")(tbl_B, 1:6, 2, 
      matrix(NA, 6, 1))

tbl_A %>% 
  set_background_color(everywhere, 1:2, cbind(colors1, colors2)) %>% 
  huxtable::add_colnames() 

C 部分,因此,颜色映射不是在单个列中完成,而是在整个表格中完成:

colors_all <- by_colorspace("orange", "white", "green")(tbl_B, 1:6, 1:2, 
  matrix(NA, 6, 2))

tbl_A %>% 
  set_background_color(everywhere, 1:2, colors_all) %>% 
  huxtable::add_colnames() 

更新。在可能会变成 huxtable 4.8.0 的 github master 中,您现在确实可以这样做:

tbl_A %>% 
  map_background_color(everywhere, 1:2, 
    by_colorspace("orange", "white", "green", colwise = TRUE))

而不是为每一列单独调用map_...

【讨论】:

  • 非常感谢@dash2 为您提供出色且非常有用的解决方案!也非常感谢您考虑在 huxtable 4.8.0 中包含 colwise = TRUE 选项。
  • 很高兴。现已推出(实际上在 4.7.1 中)。
猜你喜欢
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多