Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automated ggplot2 example gallery in knitr

Tags:

r

ggplot2

knitr

I'm trying to produce a gallery of ggplot2 geoms using knitr. In order to do this quickly I thought to use the built-in examples to populate the content.

After some trial and error I've got to this point:

\documentclass[a4paper,titlepage]{tufte-handout}
\usepackage{pdflscape}
\usepackage{graphicx}
\usepackage{alltt}

<<setup, include=FALSE, cache=FALSE>>=
options(replace.assign=TRUE,tidy=TRUE)
library(ggplot2)
library(plyr)
library(scales)
geoms <- setdiff(apropos("^geom_"),"geom_blank")
@

\title{ggplot2 Gallery}

\begin{document}
\maketitle

<<examples, echo=FALSE, comment=NA>>=
for(i in geoms){
    writeLines(paste0("\\section{",gsub("_","\\\\_",i),"}"))
    do.call("example",list(i))
}
@

\end{document}

But there are still a number of issues I can't resolve:

  • I can't seem to be able to mix markup and asis results options within the chunk so that section headings get produced. (This will be crucial for navigation of the document later). Is there any other way of producing writing LaTex within the chunk?

  • There are some examples which throw errors (which is why geom_blank is excluded). The knitr documentation states that computation continues in the case of errors, but it only seems to be the knit process which continues; the example loop ceases at that point. Is there a way to avoid the parts of the examples that are errors?

  • The example code output isn't syntaxed highlighted. (Useful but not essential).

like image 588
James Avatar asked Jul 25 '12 15:07

James


1 Answers

See 021-ggplot2-geoms.Rnw for the full code. The basic idea is to construct the code chunks before knit them. The code is short, so probably I do not need to explain it too much.

In theory you should be able to get something like this (more than 200 pages of ggplot2 examples):

ggplot2 geoms generated by knitr

like image 164
Yihui Xie Avatar answered Oct 17 '22 03:10

Yihui Xie