如何用 tableGrob 显示 table 的标题?
how to show the title of a table with tableGrob?
考虑这个例子
library(gridExtra)
library(grid)
d1 <- head(iris[,1:3]) %>% as_tibble()
d2 <- head(iris[,2:5]) %>% as_tibble()
grid.arrange(tableGrob(d1),
tableGrob(d2))
这给出了
这真的很好,但我缺少数据框的标题!如何自动将它们添加到图片中?
谢谢!
您可以使用 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)
我建议在 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))
考虑这个例子
library(gridExtra)
library(grid)
d1 <- head(iris[,1:3]) %>% as_tibble()
d2 <- head(iris[,2:5]) %>% as_tibble()
grid.arrange(tableGrob(d1),
tableGrob(d2))
这给出了
这真的很好,但我缺少数据框的标题!如何自动将它们添加到图片中?
谢谢!
您可以使用 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)
我建议在 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))