如何按表格中的大小和颜色编号格式化文本(tableGrob)?

时间:2017-05-30 15:41:47

标签: r

使用AkselA提供的解决方案。在How to formatting numbers by column in a table (tableGrob) 中,我试图增加表格中的字体大小。

从这个网站,我相信解决方案是在#34;访问表中的现有grob"部分使用:

g$grobs[ind][[1]][["gp"]] <- gpar(fontsize=15, fontface="bold").

但是当我尝试更改代码时,我不断收到错误。

1 个答案:

答案 0 :(得分:0)

我能够找到这个问题的答案。我能够使用&#39; 42提供的解决方案 - &#39;在Text alignment and font size in gtable

更改他的代码片段并将其添加到引用问题的末尾。

g$grobs[] <- 
 lapply(g$grobs[], 
 function(x) modifyList( x, list(gp=list(fontsize=25, cex=1) ) ) )

完整的代码是:

    library(gtable)
library(grid)
library(gridExtra)
library(zoo)

data(iris)
iris <- iris[1:4, 1:3]
rownames(iris) <- as.character(as.yearmon(
  seq(as.Date("2000/1/1"), as.Date("2000/4/1"), by = "month")))
iris$RankColumn <- 1:nrow(iris)

# a simple function to scale each row or column to the range [0, 1]
# will convert characters to numerics if in a sensible format
norm <- function(x, mar=2) {
    rnames <- rownames(x)
    x <- apply(x, 2, as.numeric)
    x <- apply(x, mar, function(y){(y-min(y))/(max(y)-min(y))})
    rownames(x) <- rnames
    x
}

# function to pad with zero
# by default does not pad integers
zeropad <- function(x, nz=1, exc.int=TRUE) {
    if (is.integer(x) & exc.int) {
        x
    } else { 
        sprintf(paste0("%.", nz, "f"), x)
    }
}

bluecol <- colorRamp(c("#3366EE", "#AABBFF", "#DDDDFF"))(norm(iris))
bluecol <- rgb(bluecol[, 1], bluecol[, 2], bluecol[, 3], max=255)

tt <- ttheme_default(core=list(bg_params=list(fill=bluecol)))

# convert floats to zero-padded characters
iris[1:ncol(iris)] <- sapply(iris, zeropad, 2)

g <- tableGrob(iris, theme=tt)
g <- gtable_add_grob(g,
                     grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
                     t = 2, b = nrow(g), l = 1, r = ncol(g))
g <- gtable_add_grob(g,
                     grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
                     t = 1, l = 1, r = ncol(g))


g$grobs[] <- 
   lapply(g$grobs[], 
     function(x) modifyList( x, list(gp=list(fontsize=25, cex=1) ) ) )


plot.new()
grid.draw(g)