【问题标题】:How to add name of column in column of rownames in tableGrob in R?如何在R中tableGrob的行名列中添加列名?
【发布时间】:2019-01-25 17:25:45
【问题描述】:

我正在尝试从 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)

在输出中,rownames (2004, 2005....) 的列名是空白的。我需要将其命名为“年份”。有人可以帮助并指导我如何做吗?

【问题讨论】:

  • 请编辑您的问题以使其完全可重现。 ttheme_minimal 是什么?您可以在 r-tag wiki 下阅读有关可重复性的信息。提供最少的、可重复的、有代表性的示例以及所需的最终结果。对数据使用dput(),并指定所有带有库调用的非基础包。

标签: r ggplot2 charts gridextra gtable


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2014-11-20
    • 2020-10-05
    相关资源
    最近更新 更多