gridextra - gridExtra 使用 tableGrob 为不同的列着色
问题描述
我对 gridExtra 包中的 tableGrob/grid.table 有疑问。有没有办法为每列自定义不同的颜色?到目前为止,在这个 stackoverflow 链接中,我只找到了如何针对不同的行或特定于单元格进行自定义。
如果可能的话,非常感谢任何建议!
解决方案
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)
推荐阅读
- apache-kafka - 对 Apache Kafka 的澄清
- python - 优化执行速度,提高代码可读性
- javascript - 如何在光滑的轮播上使用动态数据?
- c++ - 通过 WinAPI 计算每个内核的 CPU 使用率
- java - 尝试将来电重定向到android中的自定义UI
- python - 可以从模型中获取产品名称
- reactjs - MUI 风格的组件 + 一个新的道具(Typescript)
- php - HTML 中的 PHP 导致 SyntaxError: Invalid or unexpected token 错误?
- python - 将 zip 文件转换为 bytea 以存储在 postgres 中 - python
- security - Windows 10 和以“cookies”开头的文件名