Knitr在同一块中改变了数字大小

时间:2016-06-23 17:38:19

标签: r latex height knitr figure

我有一个R循环,它使用metafor在每次迭代中生成一个森林图。森林图每个样本有一行,每次迭代都有不同数量的样本,所以我需要高度变化很大(目前在2.5到8英寸之间)。

我尝试了几个选项,例如this one,但无论我做什么,我创建的每个图形在.pdf文件输出中都具有相同的高度(似乎只是使文件正方形),只有上方和下方的白色边缘非常大。

我还在自定义图形设备here上找到了该注释,但我不知道如何在一个块中间更改图形设备。我试着在每次循环迭代中简单地使用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 个答案:

答案 0 :(得分:0)

\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对类似问题的回答。