Knitr vary figure size in the same chunk

妖精的绣舞 提交于 2019-12-01 07:52:53

问题


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}

回答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.



来源:https://stackoverflow.com/questions/37998364/knitr-vary-figure-size-in-the-same-chunk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!