gpt4 book ai didi

r - gridExtra使用tableGrob为不同的行着色

转载 作者:行者123 更新时间:2023-12-04 04:05:45 24 4
gpt4 key购买 nike

我有一个关于gridExtra包中的tableGrob/grid.table的问题。使用常规参数设置,可以直接为备用行着色。但是,我希望对行的颜色进行更多控制可能是可行的。

例如,是否可以用不同的颜色为每三行着色?
我怀疑通过这个链接中的示例判断,grid.edit函数是解决此问题的一种方法:http://code.google.com/p/gridextra/wiki/tableGrob但我不知道如何将其应用于我的问题。

我相信发布这个问题的人也有同样的想法。 Table with rows of different colors with tableGrob

由于兼容性问题,我目前仍停留在R 2.13上,因此,如果有不涉及较新版本的建议,那将是理想的选择。

示例代码:

library(gridExtra)

grid.table(mtcars[1:10, ],
gpar.coretext = gpar(fontsize = 10),
gpar.corefill = gpar(fill = "lightblue", alpha=0.5, col = NA),
h.even.alpha = 0.5
)

最佳答案

从gridExtra的v> = 2.0.0开始,grid.table现在基于gtable,并且可以自定义到比以前版本更深的级别。 vignette has more examples,但是为了完整起见,这里的示例说明了如何突出显示特定的单元格,

g <- tableGrob(iris[1:4, 1:3])
find_cell <- function(table, row, col, name="core-fg"){
l <- table$layout
which(l$t==row & l$l==col & l$name==name)
}

ind <- find_cell(g, 3, 2, "core-fg")
ind2 <- find_cell(g, 2, 3, "core-bg")
g$grobs[ind][[1]][["gp"]] <- gpar(fontsize=15, fontface="bold")
g$grobs[ind2][[1]][["gp"]] <- gpar(fill="darkolivegreen1", col = "darkolivegreen4", lwd=5)
grid.draw(g)

编辑:上面的功能很容易“矢量化”
find_cells <- function(table, row, col, name="core-fg"){
l <- table$layout
unlist(Map(function(r, c) which(((l$t-1) == r) & ((l$l-1) == c) & (l$name == name)), row, col))
}

modify_cells <- function(g, ids, gp=gpar()){
for(id in ids) g$grobs[id][[1]][["gp"]] <- gp
return(g)
}

ids <- find_cells(g, 1:3, c(3,2, 1), "core-fg")
g <- modify_cells(g, ids, gpar(fontsize=15, fontface="bold"))

grid.newpage()
grid.draw(g)

enter image description here

请注意,在大多数情况下,在表构建过程中指定参数会更有意义,
faces <- sample(1:4, size = prod(dim(iris[1:4, 1:2])), replace = TRUE)
tt <- ttheme_default(core=list(fg_params=list(fontface=faces)))

grid.table(iris[1:4, 1:2], theme=tt)

enter image description here

关于r - gridExtra使用tableGrob为不同的行着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18414001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com