首页 > 解决方案 > gridExtra 使用 tableGrob 为不同的列着色

问题描述

我对 gridExtra 包中的 tableGrob/grid.table 有疑问。有没有办法为每列自定义不同的颜色?到目前为止,在这个 stackoverflow 链接中,我只找到了如何针对不同的行或特定于单元格进行自定义。

如果可能的话,非常感谢任何建议!

标签: gridextra

解决方案


grid.table 列颜色/填充:此示例是单个列的渐变填充。

library(grid)
library(gridExtra)
library(scales)
library(dplyr)

# build a vector color/fill choice for the first two columns
blkz <- rep(c("NA", "NA"), times = c(4,4))  #NA is for transparent

# generate continuous color scales based off a vector of colors from https://themockup.blog/posts/2020-05-16-gt-a-grammer-of-tables/
red_color_generator <- scales::col_numeric(c("red", "white"), domain = NULL)

redz2 <-red_color_generator(seq(10, 60, by = 10))[1:4] #%>% scales::show_col()

# cmobine the two vectors
blkz_redz <- c(blkz, redz2)

tt <- ttheme_default(core=list(bg_params=list(fill= blkz_redz, col = "gray56")))
dev.off()
grid.table(iris[1:4, 1:3], theme=tt)

在此处输入图像描述

#~~~~~~ 以变量中的值为条件进行颜色填充。请按照以下步骤操作。

#conditional color mapper function
clrize <- 
  function(df, x) {
                   df %>% 
                       mutate(cc =
                              ifelse(x == 1.3, "#FFB299",
                              ifelse(x == 1.4, "#FF8969",
                              ifelse(x == 1.5, "#FF5B3A", 
                              "#FF0000"))))
                }


#map this to the column build a vector
dt <- iris[1:4,1:3] %>% as.data.frame()  

# apply color based on the value on petal.length variable        
clrize(dt, dt$Petal.Length)  -> redz3

# cmobine the two vectors
blkz_redz <- c(blkz, redz3$cc) # cc is var added inside the function

tt <- ttheme_default(core=list(bg_params=list(fill= blkz_redz, col = "gray56")))
dev.off()
grid.table(iris[1:4, 1:3], theme=tt)

在此处输入图像描述


推荐阅读