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

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:

Varying widths for graphs in a loop using the pander package

Results for: mpg

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

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:

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

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

  1. Hi! Quick question that’s totally off topic. Do you know how to make your site mobile friendly? My site looks weird when viewing from my iphone4. I’m trying
    to find a template or plugin that might be able to correct
    this issue. If you have any recommendations, please share.

    With thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>