I am trying to produce multiple plots in one knitr chunk using a loop. This is not so hard, I just need to wrap each plot in a print() statement and knitr automatically generates appropriate filenames, e.g. chunkname1.pdf, chunkname2.pdf...
However, my plots are vary significantly in height and I need to specify fig.height
for each plot. No problem, I'll just specify a vector of heights (e.g., fig.height=c(7,9)
). In this case, knitr not so wisely produces two graphs with the same file name (the last overwriting the first). Consistent with Yihui's hack, I decided I could vectorize over the two cases with fig.ext=paste0(c("A","B"),".pdf")
. This sort of works works and produces output chunkname1.A.pdf
of height 7 and chunkname2.B.pdf
of height 9 (it also produces chunkname1.B.pdf
of height 9 and chunkname2.A.pdf
of height 7).
Worse, in this latter case the generated tex output incorrectly references chunkname1
and chunkname2
, which of course cannot be found. In Yihui's hack he directly references the generated files by their hacked names, something I do not care to do.
So, what is the "right" way to deal with this? The documentation leads me to believe that fig.height
is vectorized over graphs but now I see that is only referring to the combination of output devices, file extensions/paths, etc, for generating multiple, different versions of the same plot. But it provides no assistance whatever for specifying varying attributes of intrinsically different plots, even though knitr supports multiple plots per chunk.
This leads me to one of two conclusions:
Multiple plots per chunk should be avoided except in simple cases (preferring to specify plots in separate chunks, with appropriate chunk options).
knitr could be improved by vectorizing over both chunk options and/or unique plots per chunk; e.g.
fig.height=c(7,9)
would size chunkname1.pdf at 7 and chunkname2.pdf at 9, as I naively expected. How to do this (based on my cursory inspection of output.R) correctly, or whether it is possible, is not clear to me.
Option 1 is obviously flawed (in my use case, I only specify the number of plots, or models, at run time, and I want to avoid a slew of missing plot errors). Option 2 seems like the more R-ish way to do things, if it is not impossible for obscure reasons. So, is there a way to accomplish multiple plots per chunk with different heights, or is this a bug/feature request for knitr?