#+TITLE: Generating PGF graphics from R in org-babel #+AUTHOR: Austin F. Frank #+EMAIL: austin.frank@gmail.com #+DATE: 2009-12-11 Fri #+LANGUAGE: en #+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t #+OPTIONS: TeX:t LaTeX:t skip:nil d:nil todo:t pri:nil tags:not-in-toc #+LATEX_HEADER: \usepackage{tikz} Recently a new =R= package, =pgfSweave=, was announced.[fn:1] This package boasts a fascinating capability: generating all R graphics as \{LaTeX} code that will be typeset using the tikz package and included as PGF graphics.[fn:2] This is an appealing option for several reasons: 1. Scaling of size and adjustments of position should be handled seamlessly and without loss of resolution 2. Colors can be specified identically for graphics and any other markup in the $\LaTeX$ document 3. Since they're just more $\LaTeX$ code, graphics can be manually edited in emacs 4. Same fonts will be used for text in figures as are used in the text of the document 5. $\LaTeX$ markup can be used in figure text 6. tikz integrates nicely with Beamer Given this list of features, I decided to see whether I could get similar functionality in org-babel. * R code ** Load =tikzDevice= First, we need to load the packages required for producing tikz output in =R=. If all goes well, you should get a message about the paths to the various programs required to generate $\LaTeX$ markup from within =R=. #+source: load_tikzDevice #+BEGIN_SRC R :results output :exports both :cache ## I want to show the messages that are generated when the package is ## loaded. These are printed to the equivalent of stderr, so I have ## to rewrite the `message' function to produce output that I can ## print back later. tikz.message <- capture.output(withCallingHandlers(library(tikzDevice), message = function (m) cat(m$message))) cat(tikz.message, sep="\n") #+END_SRC ** R example #+source: lmer_example #+BEGIN_SRC R :results output :exports both :cache :session ## I use this library all the time library(lme4) ## here's the standard example m <- lmer(Reaction ~ Days + (1 | Subject), sleepstudy) print(m) #+END_SRC ** Graphics creation #+source: tikz_example #+BEGIN_SRC R :results file :exports code :cache :session library(tikzDevice) ranef.m <- ranef(m, postVar = TRUE) tikz(file = "ranef.tex", width=4, height=4) print(qqmath(ranef.m)) dev.off() #+END_SRC #+BEGIN_CENTER #+CAPTION: sample graphics \input{ranef} #+END_CENTER * Footnotes [fn:1] http://thread.gmane.org/gmane.comp.lang.r.packages/351 [fn:2] http://sourceforge.net/projects/pgf/