在R中的TableGrob中添加标题

时间:2018-11-01 16:37:54

标签: r ggplot2 gridextra

我的地块中有一张桌子,我想在桌子上添加标题。 这是我的代码:

    pl <- ggplot(artsci,aes(Preferred.Class.Year))
pl2 <- pl + geom_bar(aes(fill=Gender)) + 
  scale_x_continuous(breaks = seq(1908,2020,by=2)) +
  scale_y_continuous(breaks=seq(0,40000,by=1000)) +
  coord_flip() + theme_bw() +
  scale_fill_manual(values = c('steelblue4','paleturquoise3'))+
  labs(y='Count',x='Preferred Class Year') +
  annotation_custom(tableGrob(minitbl,rows = NULL,theme = mytheme),
                    xmin=1940, xmax=1946, ymin=3500, ymax=3500) 
print(pl2) 

我已附上图片以显示我的结果。我找不到为表添加标题的解决方案。作为一种解决方法,我刚刚添加了标为“顶级年份”的行,但我不想坚持下去。见下图

image of plot

1 个答案:

答案 0 :(得分:1)

查看此post

我做了一个函数来做到这一点:

myTableGrob <- function(data_dt, title_v, fontsize_v = 14){
  #' Create custom table grob with title
  #' @description Creates table grob in format that is most common for my usage.
  #' @param data_dt Data.table that the grob will be made out of
  #' @param title_v Title for display
  #' @param fontsize_v Fontsize for title. Default is 14 (goes well with my_theme)
  #' @value gtable object
  #' @export

  ## Table
  table_grob <- tableGrob(data_dt, rows = rep('', nrow(data_dt)), theme = ttheme_minimal())
  ## Title
  title_grob <- textGrob(title_v, gp = gpar(fontsize = fontsize_v))
  ## Add title
  table_grob <- gtable_add_rows(table_grob, heights = grobHeight(title_grob) + unit(5,'mm'), pos = 0)
  table_grob <- gtable_add_grob(table_grob, title_grob, 1, 1, 1, ncol(table_grob), clip = "off")
}

用法:

# Dependencies
library(gridExtra)
library(gtable)

# Data
data_mat <- cbind(LETTERS[1:5], letters[1:5], 1:5, 20:16)

# Grobs
default_grob <- myTableGrob(data_mat, "Default")
smallText_grob <- myTableGrob(data_mat, "Small Font Size", fontsize_v = 8)
longTitle_grob <- myTableGrob(data_mat, "Title is Longer than the Table")

# Plot
grid.newpage(); grid.draw(default_grob)
grid.newpage(); grid.draw(smallText_grob)
grid.newpage(); grid.draw(longTitle_grob)