你的问题解决方案可能与
这个问题非常相似。然而,我认为你的问题更加普遍,所以我会尽量提供更一般化的解决方案...
据我所知,在图形环境中添加额外的LaTeX代码并没有简单的解决方案。你可以更新钩子(即图形块生成的LaTeX代码)
knit(或输出)钩子。
LaTeX图形输出钩子的源代码可以在
这里(hook_plot_tex
)找到。生成的输出从
第159行开始。在这里,我们可以看到输出的结构,并且在它到达LaTeX引擎之前修改它。
然而,我们只想为相关的图形块修改它,而不是所有图形块。这就是
Martin Schmelzer的答案有用的地方。我们可以创建一个新的块选项,允许控制何时激活它。例如,启用使用
caption*
和
floatrow
,我们可以定义以下knit钩子。
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)
})
我们正在做的是 (1) 用
\caption*
替换
\caption
命令,(2) 定义自定义的 floatfoot 文本输入,(3) 用
\floatfoot{custom text here}\end{figure}
替换
\end{figure}
,使
floatfoot
在 figure 环境中。
正如您可能已经注意到的那样,在 figure 环境中,您可以添加/替换的内容不限。只需确保它被添加到环境中并位于适当位置即可。请参见下面的示例,了解如何使用 chunk 选项启用
floatfoot
和
caption*
。(您还可以通过将
!is.null(options$customplot)
条件分割来将
customplot
选项拆分为例如
starcaption
和
floatfoot
。这应该允许更好的控制)
工作示例:
---
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
选项。应该很容易解决,但我没有时间去研究它。