Search code examples
rlatexsweave

Generating beanplots in a forloop with LaTeX


I am trying to automatically generate a number of beanplots with a forloop, and outputting them into a LaTeX document. Starting with a data frame (that successfully generates beanplots), I am using the code below. The intent is to output consecutive beanplots into the document. I am able to do this by writing a beanplot command for each desired plot (it works fine), but obviously this would be much nicer if I could do it with a forloop. However, when I try to use a forloop, instead of outputting say 9 plots, it only outputs the last plot. Any ideas on why this is? I tried using fig.keep='all' and plot.new(), neither helped. Compiling with Sweave. Thanks!

<<beanplots,fig.keep='all'>>=
#fig.keep='all' <- this did not help
suppressPackageStartupMessages(require(beanplot))
for (i in length(unique(Data[['Days']]))){
   # plot.new()   ##  this did not help either
  beanplot(Readings~FactorLevels,
         data=subset(x=Data, subset=(Data[['Days']]==i)),
         main=paste("Day",i,sep=" "),
         cex.axis=0.7)
}
@

Solution

  • beanplot works with the Lattice graphics library. As such, it does not automatically produce plots when running non-interactively. You must explicitly call print() on the object returned by the call to produce a plot. Try

    <<beanplots,fig.keep='all'>>=
    #fig.keep='all' <- this did not help
    suppressPackageStartupMessages(require(beanplot))
    for (i in unique(Data[['Days']])){
       # plot.new()   ##  this did not help either
      print(beanplot(Readings~FactorLevels,
             data=subset(x=Data, subset=(Data[['Days']]==i)),
             main=paste("Day",i,sep=" "),
             cex.axis=0.7))
    }
    @