Table as an Image in R

October 24, 2013
By

(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.

library(OIdata)
data(birds)
library(ggplot2)
library(gridExtra)

# 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 his blog: Mollie's Research Blog.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: 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.