您的问题的解决方案可能与this one 非常相似。不过,我相信你的比较笼统,所以我也会尽量笼统一点……
据我所知,没有简单的解决方案可以在图形环境中添加额外的 LaTeX 代码。您可以做的是更新knit (or output) hook(即图形块生成的LaTeX代码输出)。
LaTeX 图形输出钩子的源代码可以在here (hook_plot_tex) 找到。可以从line 159 开始找到生成的输出。在这里我们可以看到输出的结构,我们可以在它到达乳胶引擎之前对其进行修改。
但是,我们只想为相关的图形块修改它,而不是全部。这就是Martin Schmelzer's answer comes in handy。我们可以创建一个新的块选项,允许控制它何时被激活。作为启用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)
})
我们在这里所做的是 (1) 将 \caption 命令替换为 \caption*,(2) 定义自定义 floatfoot 文本输入,(3) 将 \end{figure} 替换为 \floatfoot{custom text here}\end{figure},这样 floatfoot在 figure 环境中。
正如您可能知道的那样,在 figure 环境中可以添加/替换的内容是无限的。只需确保将其添加到环境中并位于适当的位置即可。请参阅下面的示例,如何使用块选项启用 floatfoot 和 caption*。 (您还可以将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()
```
PS
上面的示例需要启用fig.align 选项。应该很容易修复,但我没有时间研究它。