在使用R中的gridextra时,向tableGrob添加多行脚注。

4
我最近开始使用tableGrob和gridextra来合并多个图表和表格。我想让我的tableGrob有一个脚注和标题。
以下链接很好地回答了这个问题:Adding text to a grid.table plot 但是在上面的代码中,如果脚注太长,它会被截断。请问有人能否提供一种替代方法,使得脚注在到达表格末尾时自动换行?如果可以在单词中间换行,那也可以。
test <- data.frame(boo = c(20,1), do = c(2,10), no = c(3,5),co = c('ed','jeff'))

t1 <- tableGrob(test)

tw <- convertWidth(unit(grobWidth(t1),'npc'),
                   "in", valueOnly = T)

title <- textGrob("Title is long too or is it??",gp=gpar(fontsize=15))
footnote <- textGrob("footnote is pretty longgg but not unusually longgggggggggkjwd jwkldn", x=0, hjust=0,
                     gp=gpar( fontface="italic"))

padding <- unit(0.5,"line") 

t1 <- gtable_add_rows(t1, 
                        heights = grobHeight(title) + padding,
                        pos = 0)
t1 <- gtable_add_rows(t1, 
                        heights = grobHeight(footnote)+ padding)
t1 <- gtable_add_grob(t1, list(title, footnote),
                        t=c(1, nrow(t1)), l=c(1,1), 
                        r=ncol(t1))

grid.arrange(t1)

长注释表格Grob

当我将绘图和表格组合在一起时,我希望这个功能也能正常工作。请帮忙。

我尝试使用strwrap并将宽度设置为grobWidth,但是对我没有用。

1个回答

4
RGraphics书籍/软件包提供了可能的解决方案。
splitString <- function (text, width) {
  strings <- strsplit(text, " ")[[1]]
  newstring <- strings[1]
  linewidth <- stringWidth(newstring)
  gapwidth <- stringWidth(" ")
  availwidth <- convertWidth(width, "in", valueOnly = TRUE)
  for (i in 2:length(strings)) {
    width <- stringWidth(strings[i])
    if (convertWidth(linewidth + gapwidth + width, "in", 
                     valueOnly = TRUE) < availwidth) {
      sep <- " "
      linewidth <- linewidth + gapwidth + width
    }
    else {
      sep <- "\n"
      linewidth <- width
    }
    newstring <- paste(newstring, strings[i], sep = sep)
  }
  newstring
}


tit <- "Title is long too or is it??"
foot <- "footnote is pretty longgg but not unusually longgggggggggkjwd jwkldn"
footnote <- textGrob(splitString(foot, sum(t1$widths)))
title <- textGrob(splitString(tit, sum(t1$widths)))
t1 <- gtable_add_rows(t1, heights = grobHeight(footnote))
t1 <- gtable_add_rows(t1, heights = grobHeight(title), 0)
t1 <- gtable_add_grob(t1, list(title, footnote),
                      t=c(1, nrow(t1)), l=1, r=ncol(t1))

grid.draw(t1)

这个很好用,Baptiste。有几个问题不太好: 1)脚注是否可以在单词中间断开? 2)宽度能否自动检测脚注的字体大小,以便使用表格的宽度? 例如,当我使用字号为7或10时,会有所不同,如果太长,它将被裁剪在表格末尾?如果换行可以根据脚注字体大小进行调整,那就太好了。这可能要求过高了! :) 但上述解决方案非常好用! - StatMan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接