上图中使用knitr的说明(LaTeX/PDF)
我想用texmaker中的knitr将标题放在图形上方。 ,我知道目前建议的解决方案是:上图中使用knitr的说明(LaTeX/PDF),latex,knitr,caption,texmaker,Latex,Knitr,Caption,Texmaker,我想用texmaker中的knitr将标题放在图形上方。 ,我知道目前建议的解决方案是: \begin{figure} \caption{This is a caption above the figure} <<a-plot, echo=FALSE>>= plot(1) @ \end{figure} \begin{figure} \标题{这是图上方的标题} = 地块(1) @ \结束{图} 但这样我就无法显示代码(因为echo=FALSE)。 如果我
\begin{figure}
\caption{This is a caption above the figure}
<<a-plot, echo=FALSE>>=
plot(1)
@
\end{figure}
\begin{figure}
\标题{这是图上方的标题}
=
地块(1)
@
\结束{图}
但这样我就无法显示代码(因为echo=FALSE
)。
如果我选择的是echo=TRUE
,我得到的是标题,然后是代码,然后是图形,这也不是我想要的。
我想展示的是R
的代码,(以及)用R
代码绘制的图形,图形上方有标题。尝试使用钩子:
<<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}
=
f这是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)
f我倾向于使用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
选项添加到块头。非常感谢您的回答!但我试图准确地使用您的示例,我从Texmaker收到一条错误消息,说“找不到对象‘knit_hooks’”。我是texmaker、knitr和hook的新手。你知道为什么这对我不起作用吗?@Serena insertlibrary(knitr)
在第一部分的开头。非常好的解决方案,谢谢!但是有两个缺点:1)需要自己添加\ begin{figure},2)需要将fig.cap更改为新的figT。第一个问题很容易解决(只需在f中添加:\\begin{figure}\n,“\\end{figure}\n”)。第二个问题似乎很难解决,因为使用fig.cap会触发在图下方自动插入\标题,而避免这种情况的唯一方法似乎是完全重写hook\u plot\u tex。。。