Thursday, February 2, 2012

Using pgfSweave Package for R

pgfSweave can generate a latex document with R code in it. This means that plots are updated automagically, but setting up/getting used to it can be a big pain. The difference between pgfSweave and Sweave is that latter cannot cache plots. Hence, if one uses packages like ggplots, the report generation can be much slower than using pgfSweave.

To use pgfSweave, start with putting this in the preamble
\documentclass{article}

\usepackage{tikz}
\tikzset{external/system call={latex \tikzexternalcheckshellescape -halt-on-error
-interaction=batchmode -jobname "\image" "\texsource";
dvips -o "\image".ps "\image".dvi;}}

\begin{document}

<<setup,echo=F>>=
setCacheDir("cache")
options(keep.space=TRUE)
@

<<data,cache=T,tidy=T>>=
# hey, a comment
data(airquality)
print(kruskal.test( Ozone ~ Month, data = airquality )) # and another
@

\begin{figure}[!ht]
\centering
%notice the new options
{\pgfkeys{/pgf/images/include external/.code={\includegraphics[width=6in]{#1}}}
<<boxplot,cache=T,echo=T,fig=T,width=3,height=3,tikz=T,external=T,highlight=T>>=
boxplot(Ozone ~ Month, data = airquality,
main='Ozone distribution',xlab='Month',ylab='Concentration')
@
}% this brace ends the effect of 'include external'
\caption{This is from pgfSweave. Text is typset by \LaTeX\ and so matches the
font of the document.}
\end{figure}

\end{document}


Following inserts a cleaned up (and highlighted) code block whose result is cached <<data,cache=T,tidy=T>>=
# hey, a comment
data(airquality)
print(kruskal.test( Ozone ~ Month, data = airquality )) # and another
@


Following inserts a plot of size 2x2 sq.in. and embeds it at size 3x3 sq.in. \begin{figure}[!ht]
\centering
%notice the new options
{\pgfkeys{/pgf/images/include external/.code={\includegraphics[width=3in]{#1}}}
<<boxplot2,cache=T,echo=T,fig=T,width=2,height=2,tikz=T,external=T,highlight=T>>=
boxplot(Ozone ~ Month, data = airquality,
main='Ozone distribution',xlab='Month',ylab='Concentration')
@
}% this brace ends the effect of 'include external'
\caption{This is from pgfSweave. Text is typset by \LaTeX\ and so matches the
font of the document.}
\end{figure}


The Makefile from pgfSweave package shows how to compile things.
R CMD pgfsweave --pgfsweave-only pgfSweave-latex-example.Rnw
latex pgfSweave-latex-example.tex
make -f pgfSweave-latex-example.makefile
latex pgfSweave-latex-example.tex
dvipdf pgfSweave-latex-example.dvi


This post was useful.

No comments:

Post a Comment