如何使用 knit/rmarkdown 自定义图形 LaTeX

Bil*_*ney 5 r knitr r-markdown

我想在通过 LaTeX 生成 .pdf 文件的 rmarkdown 文档中使用 ggplot2 创建的图形在浮动中创建页脚。

我的问题: rmarkdown/knitr 中有没有办法在图形环境中添加更多 LaTeX 命令?

具体来说,我想找到一种使用floatrowcaption*宏插入自定义 LaTeX 的方法,如https://tex.stackexchange.com/questions/56529/note-below-figure中所述的图形环境中所述。

当我查看块选项(https://yihui.org/knitr/options/#plots)时,类似的东西out.extra似乎接近我想要的,但是\includegraphics当我想要访问放置额外的 LaTeX 时,它被用作额外的选项在图形环境内,在任何其他 LaTeX 命令之外。

hen*_*sen 2

您的问题的解决方案可能与非常相似。然而,我相信你的更笼统一点,所以我也会尝试更笼统一点......

据我所知,没有简单的解决方案可以在图形环境中添加额外的 LaTeX 代码。您可以做的是更新knit(或输出)钩子(即由图形块生成的 LaTeX 代码输出)。

LaTeX 图形输出挂钩的源代码可以在此处找到( hook_plot_tex)生成的输出可以从第 159 行开始找到。在这里,我们可以看到输出的结构,并且我们能够在它到达乳胶引擎之前对其进行修改。

然而,我们只想修改相关的图形块,而不是全部。这就是马丁·施梅尔泽的答案派上用场的地方。我们可以创建一个新的块选项,允许控制它何时被激活。作为启用使用的示例caption*floatrow我们可以定义以下针织钩

defOut <- knitr::knit_hooks$get("plot")  
knitr::knit_hooks$set(plot = function(x, options) {  
  #reuse the default knit_hook which will be updated further down
  x <- defOut(x, options) 
  #Make sure the modifications only take place when we enable the customplot option
  if(!is.null(options$customplot)) {  
   
    x  <- gsub("caption", "caption*", x) #(1)
    inter <- sprintf("\\floatfoot{%s}\\end{figure}", options$customplot[1]) #(2)
    x  <- gsub("\\end{figure}", inter, x, fixed=T)  #(3)
  }
  return(x)
})
Run Code Online (Sandbox Code Playgroud)

我们在这里所做的是 (1) 将\caption命令替换为\caption*,(2) 定义自定义 floatfoot 文本输入,(3) 替换\end{figure}为图形环境中的\floatfoot{custom text here}\end{figure} 命令。floatfoot

正如您可能知道的那样,天空是您在图形环境中添加/替换的内容的限制。只需确保将其添加到环境中并位于适当的位置即可。请参阅下面的示例,了解如何使用 chunk 选项来启用floatfootcaption*。(您还可以通过简单地划分条件来将customplot选项拆分为例如 starcaption和。这应该可以更好地控制)floatfoot!is.null(options$customplot)

工作示例:

---
header-includes:
  - \usepackage[capposition=top]{floatrow}
  - \usepackage{caption}
output: pdf_document
---


```{r, echo = F}
library(ggplot2)

defOut <- knitr::knit_hooks$get("plot")  
knitr::knit_hooks$set(plot = function(x, options) {  
  x <- defOut(x, options) 
  if(!is.null(options$customplot)) {  
   
    x  <- gsub("caption", "caption*", x)
    inter <- sprintf("\\floatfoot{%s}\\end{figure}", options$customplot[1])
    x  <- gsub("\\end{figure}", inter, x, fixed=T)  
  }
  return(x)
})
```

```{r echo = F, fig.cap = "Custom LaTeX hook chunk figure", fig.align="center", customplot = list("This is float text using floatfoot and floatrow")}
ggplot(data = iris, aes(x=Sepal.Length, y=Sepal.Width))+
  geom_point()
```
Run Code Online (Sandbox Code Playgroud)

聚苯乙烯

上面的示例需要fig.align启用该选项。应该很容易修复,但我没有时间研究它。