Changing figure options mid-chunk (in a loop) using the pander package.

Tue 09 April 2013

Filed under nerdvana

Tags R reproducibleResearch

I wrote already about changing figure options mid-chunk in reproducible research. This can be important  e.g. if you are looping through a dataset to produce a graphic for each variable but the figure width or height need to depend on properties of the variables, e.g. if you are producing histograms and want the figures to be a bit wider when there are more bins.

That previous post was about knitr, but at the moment I am using the pander package more than knitr because it makes some things simpler. Changing figure options is a case in point.

Here is the output:

1 Varying widths for graphs in a loop using the pander package

1.0.1 Results for: mpg

loop-734
Anything you type here will be inside the same paragraph as the figure and so works like a pseudocaption

1.0.2 Results for: cyl

loop-735
Anything you type here will be inside the same paragraph as the figure and so works like a pseudocaption

 

And here is the code:

2 Varying widths for graphs in a loop using the pander package

<% for (varn in names(mtcars[,1:2))   { %><%=
var=mtcars[,varn]
pandoc.p.return(“”)
pandoc.header.return(paste(“Results for:”,varn,“”),3)
pandoc.p.return(“”)
fac=(100*log(length(unique(var))))#calculate some factor to ensure somewhat wider graphs for more bins

%><% evals.option(“width”,50+fac) %><%= #have to break out of the BRCODES to change the height options for the next chunk
qplot(var,geom=“bar”)+xlab(varn)%>
</br>Anything you type here will be inside the same paragraph as the figure and so works like a pseudocaption<%
#   coord_flip()
%><% } %>

Oh, and to make it all happen:

library(pander)

library(ggplot)

Pandoc.brew(convert=“html”,output=“loop”,“nameOfFileContainingTheAboveScript.R”)


Comments


socialdatablog © Steve Powell Powered by Pelican and Twitter Bootstrap. Icons by Font Awesome and Font Awesome More