Importing Foreign Graphics Formats into R
by Paul Murrell

The issue is how to include external graphical images in R plots?

There are two main sorts of graphics formats to consider: bitmaps (e.g., PNG, JPEG) and vector graphics (e.g., PostScript, PDF).

Importing bitmaps
The pixmap package facilitates drawing bitmaps as part of R plots. This package works with an R structure called a pixmap and there are functions for reading external files in one of the pnm (portable anymap) formats to create a pixmap. There are external applications for converting other bitmap formats to pnm.

In summary, you can take a bitmap file in any format, convert it to one of the pnm formats (e.g., using ImageMagick's convert) and then read that into R and draw it using pixmap.

Importing vector graphics

UPDATE: there is now a package grImport on CRAN for importing vector graphics into R.

Nothing exists for this yet (though see experiments below).

There are three important issues:

  1. We should select one "target" format to import. As with bimaps, there is no point in trying to directly import hundreds of different formats; software already exists to convert between different formats (e.g., GhostScript, ImageMagick, pstoedit) so we can choose one and users must convert to that format before importing to R.
  2. We have to write a reader to get the target format into R. It would be a fairly tough assignment to write something like a PostScript or PDF interpreter, but maybe something a bit simpler like FIG could be done. One option (experimented with below) is to split this into two steps: use existing tools to export the target format to a plain text format of our own design then import the plain text into R.
  3. We have to decide on how to represent the imported information in R. We could draw directly onto a graphics device, we could write R graphics expressions (i.e., a script), we could generate (grid) graphics objects, or we could create generic R objects. The last option would have the advantage of being independent of a particular graphics system; writing R code or creating grid objects would be specific to a particular graphics system. The first option would not allow us to retain R objects representing the image.

So far I have experimented a bit with PostScript as the target format, using GhostScript to convert PostScript to a custom plain text format, and reading the plain text format into generic R objects. The results of this experimentation are described here.

Importing bitmaps as vector graphics
This is harder still, but there are a couple of possibilities to consider:

  1. Convert bitmap to vector graphic using automated tool like autotrace. I personally haven't had a lot of success with trying this out.
  2. Draw bitmap in R and use locator() or grid.locator() to "trace" it. Only makes sense for quite simple shapes (i.e., only with a few vertices to trace).

I have experimented a little with the second option, as described here.