【问题标题】:Add multi-line footnote to tableGrob, while using gridextra in R向 tableGrob 添加多行脚注,同时在 R 中使用 gridextra
【发布时间】:2015-11-10 15:39:23
【问题描述】:

我最近开始使用 tableGrob 和 gridextra 来组合多个绘图和表格。我希望 mt 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)

当我在网格中也有一个绘图和一个表格时,我希望它能够工作。请帮忙。

我尝试使用 strwrap 并将宽度设置为 grobWidth,但它对我不起作用。

【问题讨论】:

    标签: r ggplot2 gridextra


    【解决方案1】:

    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.Couple 不好用的东西: 1) 脚注有什么办法可以从单词中间断开吗? 2)宽度是否可以自动检测脚注的字体大小以使用表格的宽度?例如,当我使用 7 或 10 的字体大小时会有所不同,如果它太长,它只会在表格的末尾被裁剪?如果可以根据脚注字体大小调整换行,那就太好了。这可能要求太多了! :) 但上述解决方案效果很好!
    猜你喜欢
    • 1970-01-01
    • 2013-08-27
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多