# Using tikzDevice with Sweave in R 2.13

R 2.13 introduces an option to specify a custom graphics device in an Sweave code chunk. This is really cool and allows you to use tikzDevice output like pgfSweave does. In an pinch, say when you dont have access to any non-core packages, you can use tikzDevice output with the regular Sweave driver (RweaveLatex) more simply than before. Here is a minimal example showing how.

 \documentclass{article} \usepackage[noae,nogin]{Sweave} \usepackage{tikz} \begin{document} \SweaveOpts{prefix.string=fig} Example using \texttt{tikzDevice} with the default \textbf{Sweave} driver (\texttt{RweaveLatex}).  First define a custom device: <<results=hide>>= tikz.Swd <- function(name, width, height, …){     require(tikzDevice)     tikzDevice::tikz(file = paste(name, "tikz", sep = "."),                  width = width, height = height) } @ Then use the device for plotting, but you have to include the figure manually. <<myplot, fig=T, grdevice=tikz.Swd, include=F, width=4,height=4>>= plot(1) @ \input{fig-myplot.tikz} \end{document} 

WARNING: This could be very slow if your graphic is complex

## 6 thoughts on “Using tikzDevice with Sweave in R 2.13”

1. Wow, sounds like Sweave is becoming a lot more modular! I like it.

How about including “tikz.Swd” or a similar function in pgfSweave and tikzDevice so everyone could use it with Sweave just by invoking

library(pgfSweave)

2. cameron says:

That makes sense for tikzDevice, but if you have access to pgfSweave it would be a lot better just to use the pgfSweave driver which does the same thing but more smartly.

Thanks for the suggestion.

3. cameron says:

Hi Walmes-

This feature of Sweave is only available in R 2.13 which has just been released today, I see you are using R 2.12.1, that is why you get the error “invalid value for ‘grdevice’ : tikz.Swd”.

Also, for this example you dont really need pgfSweave. This is just a proof of concept with the core Sweave RweaveLatex driver. If you are going to be heavily using tikz graphics I suggest you use pgfSweave to compile with the tikz option. There are extra options there for speeding up compilations and customizing tikz output.

4. One other suggestion would be to have an option in tikz.Swd(…, include.tex=FALSE), where, if include.tex=TRUE, to print

\includegraphics[height=,width=]{name}

so that we can just specify tex=TRUE in the chunk to have the figure included.

5. cameron says:

I agree that would be great but the \includegraphics command is hardcoded in RweaveLatex. All that tikz.Swd is allowed to do is open a graphics device. It cant really spit out anything to the tex file that includes the graphic because it is not called at the right time in the Sweave process.