[R] Can Sweave be instructed to use the cairo graphics device?

Duncan Murdoch murdoch.duncan at gmail.com
Fri Oct 8 21:33:25 CEST 2010


  On 08/10/2010 2:45 PM, Levy, Roger wrote:
> I'm writing a book using Sweave which includes Unicode characters which R's postscript and pdf graphics devices don't handle properly.  The cairo graphics device does handle these characters properly.  Thus I'd like to be able to instruct Sweave to use cairo (either sometimes or always) to produce graphics when it processes R code.  Is this possible?
>

It isn't very easy to do that, but it is possible.

There are two approaches.  The more elegant one is probably harder:  
write a new driver for Sweave, based on the existing one, and supporting 
cairo output.  You want to look at the Sweave source code to do this; in 
particular you'll end up writing your own replacement for 
RweaveLatexRuncode that knows to use cairo instead of just eps and pdf.

The easier approach is to skip Sweave's automatic handling of graphics, 
and just produce files with explicit \includegraphics calls to show 
them.  I've done this when I've wanted to include rgl graphics in a 
Sweave document.  Here's some sample code:

The first block is very rgl specific; it only happens once in the document:

<<echo=FALSE, results=hide>>=
library(rgl)
r3dDefaults$windowRect <- c(0,0, 511, 511)
snapshot <- function(name) {
    rgl.snapshot(file=paste("figs\\", name, ".png", sep=""))
    system(paste("f:\\cygwin\\bin\\convert.exe figs\\", name, ".png 
figs\\", name, ".eps", sep=""))
    system(paste("f:\\cygwin\\bin\\convert.exe figs\\", name, ".png 
figs\\", name, ".pdf", sep=""))
}
@

The next one shows the code and produces the graphic on screen:

<<>>=
open3d()
plot3d(rnorm(1000), rnorm(1000), rnorm(1000))
@

The next one saves it to a file in png format, and converts that to eps 
and pdf.  You probably don't want that conversion.

<<echo=FALSE,results=hide>>=
snapshot("sample")
@

Then some Latex code to include it.

\begin{figure}
\begin{center}
\includegraphics[width=3in]{figs/sample}
\end{center}
\end{figure}

I hope this gives you some ideas.

Duncan Murdoch



More information about the R-help mailing list