Automated ggplot2 example gallery in knitr

2020-02-04 05:56发布

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).

标签: r ggplot2 knitr
1条回答
够拽才男人
2楼-- · 2020-02-04 06:23

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

查看更多
登录 后发表回答