4

I have a R loop which produces a forest graph in each iteration using metafor. A forest graph has one line per sample, and each iteration has a different number of samples, so I need the height to vary considerably (currently between 2.5 and 8 inches).

I tried several options such as this one, but no matter what I do, each graphic I create has the same height in the .pdf file output (it seems to simply make the files square), there are just very large white margins above and below.

I also found the note on custom graphic devices here, but I don't know how to change the graphic device in the middle of a chunk. I tried to simply use opts_chunk$set(fig.width=fheight) in each loop iteration, but no luck.


MWE

\documentclass{article}

\begin{document}

 <<Mwe, echo=FALSE, results = 'asis', message='FALSE', fig.width=7,warning='FALSE'>>=

 heights <- c(2.5, 8)

 for(counter in 1:length(heights)) {
  opts_chunk$set(fig.height=heights[counter]) #This doesn't appear to change anything
  par(fin=c(7, heights[counter]) #this makes the plot have the correct height, but I get a 2.5 inch high plot vertically centered in a 7 inch high pdf. 
  hist(rnorm(100))

  cat("Some long text which describes a lot of stuff about this graphic before making a new subsection for the next one")
 }

@

\end{document}
rumtscho
  • 2,474
  • 5
  • 28
  • 42

1 Answers1

1
\documentclass{article}

\begin{document}

 <<Mwe, echo=FALSE, results = 'asis', message = F, warning = F>>=
library(knitr)
library(magrittr)

heights <- c(2.5, 8)

captions <- c("Caption 1", "Caption 2")

# Template for a plot chunk
template <- "<<plot-chunk-{{i}}, fig.height = {{ph}}, fig.cap = '{{pc}}', echo = FALSE>>=
    hist(rnorm(100))
@"

# Knit the chunk and cat() the results using knit, knit_expand
knitfun <- function(i) {
  knit_expand(text = template, i = i, ph = heights[i], pc = captions[i]) %>%
    knit(text = ., quiet = T) %>%
    cat()
}

invisible(lapply(1:2, knitfun))


@

\end{document}

I'm basing this answer on this response to a similar question.

srvanderplas
  • 424
  • 6
  • 9