Thursday, October 24, 2013

Table as an Image in R

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(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 create an empty plot, center our table in it, and use the grid.table function from the gridExtra package to display the table and choose a font size.


plot.new()
grid.table(xyTable,
  # change font sizes:
  gpar.coltext = gpar(cex = 1.2),
  gpar.rowtext = gpar(cex = 1.2))

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

The code is available in a gist.

Citations and Further Reading



5 comments:

  1. Hi,

    I'm very thankfull for your code, but could you suggest a way to speedup the plotting?
    Currently I'm working on an algorithm which merges certain rows of a dataframe, according to the values inside the data.frame.
    I would like to plot the intermediate dataframes to visualise the process of merging.
    But currently the plotting is taking longer than the merging...

    ReplyDelete
  2. Do you need them as images? If not, it would be easier to export them as text or LaTeX

    http://stackoverflow.com/questions/5465314/tools-for-making-latex-tables-in-r

    ReplyDelete
  3. why do you use ggplot2 at all here? grid.table on its own can be viewed and saved to a file just as well.

    ReplyDelete
  4. Thanks! I didn't know about grid.table. I changed the blog post to use this simpler way. The ggplot version is still available in the gist.

    ReplyDelete
  5. plot.new() should rather be grid.newpage()

    ReplyDelete