AF7
AF7

Reputation: 3242

How to plot and save tableGrob objects

Using ggplot2 and gridExtra in R, I have a tableGrob which I want to plot and save.

Let's say it is a small table like this one (you can try it yourself with the biult-in dataset iris):

ggsave(plot=tableGrob(head(iris[,1:3])), filename="test.png")

See the result:Small table

Wonderful, it works! However... lots of white space is plotted around the table, since ggsave defaults to w=7, h=7 (inches), and the table does not scale up to cover that space. I could specify w and h manually, but I have to plot many tables and it would be a lot of work to find all the right values.

If I try to plot a larger table:

ggsave(plot=tableGrob(iris), filename="test2.png")

...it does not fit anymore! Big table

So, how can I automatically tell the plotted table to readjust based on the plot size? Or how can I tell ggsave to adjust the image space to the right size?

Upvotes: 2

Views: 3689

Answers (1)

baptiste
baptiste

Reputation: 77096

tg = gridExtra::tableGrob(iris[1:40,])
h = grid::convertHeight(sum(tg$heights), "in", TRUE)
w = grid::convertWidth(sum(tg$widths), "in", TRUE)
ggplot2::ggsave("test.pdf", tg, width=w, height=h)

enter image description here

Note: the small white margin on the left is due to the rownames being right-justified, it could be removed e.g. by tweaking the padding.

Upvotes: 7

Related Questions