Tamas Ferenci
Tamas Ferenci

Reputation: 648

R grid and gridExtra: tableGrob doesn't respect width and height in viewport

I want to place several tables on a ggplot2 figure, at different locations, in different sizes, and in a way that they're dynamically resized. I welcome any better solution, but my idea was to use viewports to achieve all these aims (grid.table does have a vp argument).

However, it seems that tableGrob simply disregards the width and height settings of the vp! (Interestingly, it does understand x and y.) Here is a minimal reproducible example:

library( grid )
library( gridExtra )
data( iris )

grid.newpage()
grid.rect( vp = viewport( x = 0.4, y = 0.4, width = 0.3, height = 0.3 ) )
grid.table( iris[ 1:3, 1:2 ], vp = viewport( x = 0.4, y = 0.4, width = 0.3, height = 0.3 ) )

Upvotes: 1

Views: 1992

Answers (1)

user10389855
user10389855

Reputation: 56

tableGrob by default extends to fit the text at a given font size; if you want it to stretch to the viewport you have to manually assign custom widths/heights, at the risk of having content overflow.

library(grid)
library(gridExtra)
data(iris)

grid.newpage()
vp <- viewport(x = 0.4, y = 0.4, width = 0.3, height = 0.3) 
grid.rect(vp = vp)
tg <- tableGrob(iris[1:3, 1:2], vp = vp)
tg$widths[-1] <- rep(unit(1/2,"null"), 2)
tg$heights <- rep(unit(1/nrow(tg), "null"), nrow(tg))
grid.draw(tg)

tableGrob image

Upvotes: 3

Related Questions