【问题标题】:how to show the title of a table with tableGrob?如何使用 tableGrob 显示表格的标题?
【发布时间】:2019-01-16 12:42:31
【问题描述】:

考虑这个例子

library(gridExtra)
library(grid)

d1 <- head(iris[,1:3]) %>% as_tibble()
d2 <- head(iris[,2:5]) %>% as_tibble()

grid.arrange(tableGrob(d1),
             tableGrob(d2))

这给了

这真的很好,但我错过了数据框的标题!如何自动将它们添加到图片中?

谢谢!

【问题讨论】:

    标签: r gridextra grob


    【解决方案1】:

    你可以使用ggplot

    library(ggplot2)
    
    dd1 <- ggplot() + annotation_custom(tableGrob(d1)) + labs(title = 'd1')
    dd2 <- ggplot() + annotation_custom(tableGrob(d2)) + labs(title = 'd2')
    grid.arrange(dd1, dd2, nrow = 2)
    

    【讨论】:

    • 相当不错!!!只是跟进。假设我有几十个这样的小数据框。有没有办法将marrangeGrobtableGrob 一起使用,以便我得到一个每页都有4x4 图表的pdf?
    • 我不确定。我昨天真的遇到了annotation_customtableGrob...
    • 好的,谢谢!你知道如何摆脱灰色背景吗?看起来有点奇怪! >)
    • This link will help。如果您遇到任何问题,请告诉我
    【解决方案2】:

    我建议在 gtable 中添加一个 textGrob,

    library(magrittr)
    
    add_title <- function(g, title, padding = unit(2,"mm"), lpos=1, ...){
      tg <- textGrob(title, ...)
      g %>%
        gtable::gtable_add_rows(heights = grobHeight(tg) + padding, pos = 0L) %>% 
        gtable::gtable_add_grob(tg, t=1,b=1,l=lpos,r=ncol(g))
    
    }
    
    
    grid.arrange(tableGrob(d1) %>% add_title('a) First title', gp=gpar(fontsize=14, fontface=4), hjust=0, x=0, lpos=2),
                 tableGrob(d2) %>% add_title('b) Second title', gp=gpar(fontsize=14, fontface=4), hjust=0, x=0, lpos=2))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多