Reputation: 3242
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")
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")
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
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)
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