4

在@baptiste的这个答案的帮助下,我构建了一个快速绘制表格的函数。

plotTable<-function(data, title=NULL, footnote=NULL, fontsize=9, plotIt=TRUE, show.rownames=TRUE){
  # Generic method to plot tabular data

  # Built the base table with/without row names
  if(show.rownames){
    table <- tableGrob(data, theme=ttheme_default(
      core=list(fg_params=list(fontsize=fontsize)),
      colhead=list(fg_params=list(fontsize=fontsize)),
      rowhead=list(fg_params=list(fontsize=fontsize))))
  } else{
    table <- tableGrob(data, theme=ttheme_default(
      core=list(fg_params=list(fontsize=fontsize)),
      colhead=list(fg_params=list(fontsize=fontsize)),
      rowhead=list(fg_params=list(fontsize=fontsize))), rows=NULL)
  }

  # Set the padding
  padding <- unit(0.5,"line")

  # Add the title if it's not NULL
  if(!is.null(title)){
    title.grob <- textGrob(title, gp=gpar(fontsize=fontsize+3))
    table <- gtable_add_rows(table, heights = grobHeight(title.grob) + padding, pos = 0)
    table <- gtable_add_grob(table, list(title.grob), t=1, l=1, r=ncol(table))
  }

  # Add the footnote if it's not NULL
  if(!is.null(footnote)){
    footnote.grob <- textGrob(footnote, x=0, hjust=0, gp=gpar(fontsize=fontsize, fontface="italic"))
    table <- gtable_add_rows(table, heights = grobHeight(footnote.grob)+ padding)
    table <- gtable_add_grob(table, list(footnote.grob), t=nrow(table), l=1, r=ncol(table))
  }

  # Either plot it or return the grob
  if(plotIt) grid.arrange(table) else return(table)
}

但有时我的标题比实际表格长,而且它被切断了。

libs <- c("data.table", "grid", "gridExtra", "gtable")
lapply(libs, library, character.only = TRUE)

mytable <- data.table(x=c(1,2,3), y=c(3,2,1))
plotTable(mytable, title="Hello World")

桌子

我该如何解决?

4

2 回答 2

7

您可以手动设置表格宽度,但您需要决定应该扩展哪些列以及扩展多少。我想重新分配宽度的合理方法是为每列添加相同的边距,以便获得的总空间占标题所需的额外空间。

在此处输入图像描述

library(gridExtra)
d <- head(iris[,1:2])
table <- tableGrob(d, rows=NULL)

library(grid)
library(gtable)

title <- textGrob("my long title goes here",gp=gpar(fontsize=30))
padding <- unit(1,"line")
table <- gtable_add_rows(table, 
                         heights = grobHeight(title) + padding,
                         pos = 0)
table <- gtable_add_grob(table, title,
                         t=1, l=1, 
                         r=ncol(table))

# check whether the table width is smaller than the title width
missed <- convertWidth(sum(table$widths), "in", valueOnly = TRUE) -
  convertWidth(grobWidth(title), "in", valueOnly = TRUE)

if(missed < 0 ) # need to do something about it
  table$widths <- table$widths + unit(abs(missed)/ncol(table), "in")

grid.newpage()
grid.draw(table)
于 2015-09-01T06:08:18.203 回答
4

如果您不想调整单元格的大小,另一种选择是关闭剪裁,

table$layout$clip <- "off"

在此处输入图像描述

于 2015-09-01T06:11:20.127 回答