如何在R中的tableGrob的行名列中添加列名?

时间:2019-01-25 17:25:46

标签: r ggplot2 charts gridextra gtable

我试图从R中的矩阵输入创建一个图表。为此,我正在使用tableGrob。我的矩阵的行名称是YEAR,即2000、2001,...。 这是我现在正在使用的代码。

tt1 <- ttheme_minimal(
core=list(bg_params = list(fill = "#ffffff", alpha = 1),
          fg_params=list(fontface="bold", hjust=0, x=0.05, fontsize=9, just='centre', 
                         col=ifelse(startsWith(matrix_input, "-"), "#FF0000", "#228B22")), 
          padding=unit.c(unit(10, "mm"), unit(2.5, "mm"))
),
colhead=list(fg_params=list(fontface='bold', col='#3c3c3c', hjust=0, x=0.05, fontsize=9)),
rowhead = list(fg_params=list(fontface='bold', col='#3c3c3c', hjust=0, x=0.05, fontsize=9), 
               padding=unit.c(unit(10, "mm"), unit(2.5, "mm")))
                    )
tGrob <- tableGrob(as.matrix(matrix_input), rows = rownames(matrix_input), theme = tt1)
tGrob <- add_border_at_bottom_of_row(1)
grid.arrange(tGrob)

在输出中,行名(2004、2005 ....)的列名为空。我需要将其命名为“ Year”。有人可以帮忙指导我怎么做吗?

1 个答案:

答案 0 :(得分:1)

您可以将行名添加为数据中的新列,

library(gridExtra)
grid.table(tibble::rownames_to_column(iris[1:4,1:2], 'title'), rows=NULL)

或将其保留为行名,并在gtable单元格中手动添加标题。如果从现有表中复制textGrob并仅更改文本,则样式可能会更容易

library(gridExtra)
library(grid)

tg <- tableGrob(iris[1:4,1:2])
tg <- gtable::gtable_add_grob(tg, textGrob('title', hjust=1,x=1), t=1,l=1, b=1,r=1,z=0)
tg$layout$clip <- 'off'
grid.newpage()
grid.draw(tg)


tg2 <- tableGrob(iris[1:4,1:2])
tg2 <- gtable::gtable_add_grob(tg2, editGrob(tg$grobs[[1]], label='new'), t=1,l=1, b=1,r=1,z=0)
tg2$layout$clip <- 'off'
grid.newpage()
grid.draw(tg2)