[英]Caption above figure using knitr (LaTeX/PDF)
我想在 texmaker 中使用 knitr 将标题放在图上方。 我知道已经有人问过这个问题,而且我知道到目前为止建议的解决方案是使用:
\begin{figure}
\caption{This is a caption above the figure}
<<a-plot, echo=FALSE>>=
plot(1)
@
\end{figure}
但是这样我就无法显示代码(因为echo=FALSE
)。 如果我改为选择echo=TRUE
,我得到的是标题,然后是代码,然后是图表,这也不是我想要的。 我想展示的是R
的代码,(和)用该R
代码绘制的图形,图形上方有标题。
我倾向于使用LaTeX包来实现这样的定制:Tex StackExchange上有一个大型社区,他们开发了加载类似问题的方法。
floatrow
包可用于重新定位图上方的标题。 这在很大程度上基于之前的答案 。
使用R Markdown,因为这是目前最常用的工作流程,可以通过在YAML中包含header-includes
参数来加载包,如下所示:
---
output: pdf_document
header-includes:
- \usepackage{floatrow}
- \floatsetup[figure]{capposition=top}
---
```{r fig.cap="cap, cap, and cap"}
plot(1)
```
输出具有所需的顺序,首先显示代码,然后是标题,然后是图表。
如果不需要代码,可以将echo=FALSE
选项添加到块头。
尝试使用钩子:
<<include=FALSE>>=
f <- function(x, options) {
paste("\\end{kframe}\n",
"\\caption{", options$capT, "}\n",
hook_plot_tex(x, options),
"\n\\begin{kframe}", sep = "")
}
knit_hooks$set(plot = f)
@
\begin{figure}
<<a-plot, echo=TRUE, capT="cap, cap, and cap">>=
plot(1)
@
\end{figure}
这是kohske答案的略微修改版本,包括\\begin{figure}
和添加\\label
。 但请注意,它包含5行,而原始代码包含超过150行,因此应在非常有限的设置中使用。
f <- function(x, options) {
lab <- paste0(options$fig.lp, options$label)
paste("\\end{kframe}\n",
"\\begin{figure}\n\\caption{", options$capT, "}\\label{", lab,"}\n",
hook_plot_tex(x, options),
"\\end{figure}\n\n\\begin{kframe}", sep = "")
}
knit_hooks$set(plot = f)
在它下面添加一个同名的新块来打印代码。
\documentclass{article}
\begin{document}
\begin{figure}
\caption{This is a caption above the figure}
<<a-plot, echo=FALSE>>=
plot(1)
@
\end{figure}
<<a-plot,echo=TRUE>>=
@
\end{文档}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.