【问题标题】:Knitr vary figure size in the same chunkKnitr 在同一块中改变图形大小
【发布时间】:2016-10-26 04:27:44
【问题描述】:

我有一个 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}

【问题讨论】:

    标签: r latex height knitr figure


    【解决方案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 对类似问题的回答。

    【讨论】:

      猜你喜欢
      • 2019-05-13
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2021-07-19
      • 2012-09-23
      • 1970-01-01
      相关资源
      最近更新 更多