Table as an Image in R

October 24, 2013

(This article was first published on Mollie's Research Blog, and kindly contributed to R-bloggers)

Usually, it’s best to keep tables as text, but if you’re making a lot of graphics, it can be helpful to be able to create images of tables.

PNG table

Creating the Table

After loading the data, let’s first use this trick to put line breaks between the levels of the effect variable. Depending on your data, you may or may not need or want to do this.


# line breaks between words for levels of birds$effect:
levels(birds$effect) <- gsub(" ", "\n", levels(birds$effect))
Next let’s make our table: 

xyTable <- table(birds$sky, birds$effect)

Now we can use qplot to create an empty plot, center our table in it, and use the tableGrob function from the gridExtra package to display the table and choose a font size.

qplot(1:10, 1:10, geom = "blank") + 
theme_bw() +
theme(line = element_blank(),
text = element_blank()) +
annotation_custom(grob = tableGrob(xyTable,
# change font sizes:
gpar.coltext = gpar(cex = 1.2),
gpar.rowtext = gpar(cex = 1.2)),
xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf)

Now you can view and save the image just like any other plot.

The code is available in a gist.

Citations and Further Reading

To leave a comment for the author, please follow the link and comment on their blog: Mollie's Research Blog. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Mango solutions

RStudio homepage

Zero Inflated Models and Generalized Linear Mixed Models with R

Dommino data lab

Quantide: statistical consulting and training



CRC R books series

Six Sigma Online Training

Contact us if you wish to help support R-bloggers, and place your banner here.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)