Knitr 在同一块中改变图形大小 [英] Knitr vary figure size in the same chunk
问题描述
我有一个 R 循环,它使用 metafor 在每次迭代中生成一个森林图.森林图每个样本有一条线,每次迭代都有不同数量的样本,所以我需要高度变化很大(目前在 2.5 到 8 英寸之间).
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).
我尝试了几个选项,例如 这个,但无论我做什么,我创建的每个图形在 .pdf 文件输出中都有相同的高度(似乎只是使文件成为正方形),上面只有非常大的白边距及以下.
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.
我还在这里找到了自定义图形设备上的注释,但我不知道如何更改块中间的图形设备.我尝试在每个循环迭代中简单地使用 opts_chunk$set(fig.width=fheight)
,但没有运气.
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}
egin{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}
推荐答案
documentclass{article}
egin{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.
这篇关于Knitr 在同一块中改变图形大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!