2

I have a table within my plot and I am looking to add a title to my table. Here is my code:

    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) 

I've attached an image to show my result. I cannot find a solution to adding a title to my table. As a workaround, I've just added a row labeled as top class year but I do not want to stick with this. See image below

image of plot

Aman
  • 27
  • 6
  • 1
    Could you make your problem reproducible by sharing a sample of your data so others can help (please do not use `str()`, `head()` or screenshot)? You can use the [`reprex`](https://reprex.tidyverse.org/articles/articles/magic-reprex.html) and [`datapasta`](https://cran.r-project.org/web/packages/datapasta/vignettes/how-to-datapasta.html) packages to assist you with that. See also [Help me Help you](https://speakerdeck.com/jennybc/reprex-help-me-help-you?slide=5) & [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269) – Tung Nov 01 '18 at 16:39
  • 2
    Possible duplicate of [How can I add a title to a tableGrob plot?](https://stackoverflow.com/questions/31640916/how-can-i-add-a-title-to-a-tablegrob-plot) – Qwfqwf Nov 01 '18 at 17:14

1 Answers1

4

Check out this post.

I made a function to do this:

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")
}

Usage:

# 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)
Qwfqwf
  • 483
  • 3
  • 9