在gridExtra R中的tableGrob中包装列标题

时间:2016-03-14 14:39:02

标签: r plot graphics textwrapping gridextra

我正在创建一个R输出,其中包含2个ggplot图表和一个tableGrob

我能够插入表格,但是列名称相当长,因此整个表格不适合生成的文档。

我想仅为列标题包装文本,或者特定于每列的大小

一些代码:

library(gridExtra)
ref=c("1234567890", "0987654321")
method=c("type 1", "type 2")
methodref=c("ABC", "DEF")
firstdos=c(as.POSIXct("2015-01-01 00:00:00"), as.POSIXct("2015-02-01 00:00:00"))
lastdos=c(as.POSIXct("2015-01-31 23:45:00"), as.POSIXct("2015-02-28 23:45:00"))
dur=c("31d 0H 0M 0S", "28d 0H 0M 0S")
maxheart=c("90.25", "96")
minheart=c("40.1", "55.3")
meanheart=c("70.5", "69.4")
maxpre=c("85.6", "89.2")
minpre=c("51", "53.2")
meanpre=c("63.8", "71.1")

DF=data.frame(ref,method,methodref,firstdos,dur,lastdos,maxheart,minheart,meanheart,maxpre,minpre,meanpre)

colnames(DF)=c("Reference","Method Name","Method Reference","First Dosage taken","Duration of Medication","Final Dosage taken",
  "Maximum Heartrate (bpm)","Minimum Heartrate (bpm)","Mean Heartrate (bpm)","Maximum heartrate before trial (bpm)",
  "Minimum heartrate before trial (bpm)","Mean heartrate before trial (bpm)")

g5 <- tableGrob(head(DF))
grid.arrange(g5, nrow=1)

另外(我知道可能值得作为一个单独的问题提问),我目前正在使用grid.arrange(2个图和1个表)格式化nrow=3命令。我希望桌子坐在整个地块的顶部,第二排是两个并排的地块。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

试试这个

cols <- c("Reference","Method Name","Method Reference","First Dosage taken","Duration of Medication","Final Dosage taken",
               "Maximum Heartrate (bpm)","Minimum Heartrate (bpm)","Mean Heartrate (bpm)","Maximum heartrate before trial (bpm)",
               "Minimum heartrate before trial (bpm)","Mean heartrate before trial (bpm)")

colnames(DF) <- sapply(cols, function(x) paste(strwrap(x, width = 10),  collapse="\n"))

g5 <- tableGrob(head(DF))
grid.arrange(g5, ggplot(), ggplot(), 
             layout_matrix=matrix(c(1,1,2,3), ncol=2, byrow=TRUE))

enter image description here