Anita Pandit
Anita Pandit

Reputation: 33

tableGrob: resizing a table (changing font size) drawn on top of ggplot using annotation_custom

I'm having some issues resizing the text in a table drawn over a plot using tableGrob() and annotation_custom(). Essentially, I want the font size in the table to be smaller so that the overall table is smaller. I've checked the tableGrob() documentation and have followed it to the best of my ability, but I must be doing something wrong as it's throwing an error.

Here's a reproducible example:

library(ggplot2)
library(grid)
library(gridExtra)

df <- data.frame(x=seq(1,10),y=seq(11,20))
table <- data.frame(x=seq(1,3),y=seq(4,6))

ggplot(df,aes(x=x,y=y)) + geom_point() +
 annotation_custom(tableGrob(table,rows=NULL),xmin=0,xmax=3,ymin=15,ymax=20) # plot drawn successfully without text resizing

ggplot(df,aes(x=x,y=y)) + geom_point() + 
  annotation_custom(tableGrob(table,rows=NULL,gpar.coretext = gpar(col = "black", cex = 0.8)),xmin=0,xmax=3,ymin=15,ymax=20)
 # error when attempting to resize text following tableGrob documentation

This is the error I get when I run the second ggplot() command:

Error in gtable_table(d, name = "core", fg_fun = theme$core$fg_fun, bg_fun = theme$core$bg_fun,  : 
  unused argument (gpar.coretext = list(col = "black", cex = 0.8))

Any help is much appreciated!

Upvotes: 3

Views: 3369

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173858

If you just want all the text to be smaller in your table, use base_size in ttheme_default:

library(ggplot2)
library(grid)
library(gridExtra)

df <- data.frame(x=seq(1,10),y=seq(11,20))
table <- data.frame(x=seq(1,3),y=seq(4,6))

ggplot(df,aes(x=x,y=y)) + 
  geom_point() + 
  annotation_custom(tableGrob(table,rows=NULL, theme = ttheme_default(base_size = 8)),
                    xmin=0,xmax=3,ymin=15,ymax=20)

Created on 2020-03-05 by the reprex package (v0.3.0)

Upvotes: 3

Related Questions