Changing figure options mid-chunk (in a loop) using the pander package.
R-bloggers 2013-04-09
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
Anything you type here will be inside the same paragraph as the figure and so works like a pseudocaption
Results for: cyl
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”)
R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series,ecdf, trading) and more...