Caption above figure using knitr (LaTeX/PDF)

风格不统一 提交于 2019-11-27 14:50:51

Try using hook:

<<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} 

Michael Harper

My preference tends to be to use LaTeX packages to achieve customisation like this: there is a large community on Tex StackExchange who have developed methods to load of problems similar to this.

The floatrow package can be used to reposition the caption above the figure. This is largely based on this previous answer.

Using R Markdown, as this is the most typically used workflow these days, the package can be loaded by including header-includes argument within the YAML, as follows:

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


```{r fig.cap="cap, cap, and cap"}
plot(1)
```

The output has the desired order with the code displayed first, followed by the caption then the plot.

If the code is not wanted, the echo=FALSE option can be added to the chunk header.

Matifou

This is a slighty modified version of kohske's answer, that includes \begin{figure} and adds \label. Note however that it contains 5 lines, while the original code contains more than 150 lines, so it should be used in very limited settings.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!