Knitr如何在同一代码块中更改图像大小

4
我有一个使用metafor生成森林图的R循环。每次迭代都会产生一条样本行,而每个迭代都有不同数量的样本,所以我需要高度在相当大的范围内变化(目前在2.5到8英寸之间)。
我尝试了几个选项,例如这个,但无论我做什么,我创建的每个图形在.pdf文件输出中都具有相同的高度(它似乎只是制作正方形文件),只是在上下面有非常大的白色边框。
我还在这里找到了关于自定义图形设备的注释,但我不知道如何在块的中途更改图形设备。我尝试在每个循环迭代中简单地使用opts_chunk$set(fig.width=fheight),但没有成功。
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个回答

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}

我会根据this对类似问题的回答来回答这个问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接