Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caption above figure using knitr (LaTeX/PDF)

I would like to place the caption above the figure using knitr in texmaker. I know that this question has already been asked, and I understand that the solution suggested so far is to use:

\begin{figure} 
\caption{This is a caption above the figure} 
<<a-plot, echo=FALSE>>= 
plot(1) 
@ 
\end{figure} 

But in this way I cannot show the code (since echo=FALSE). And if I choose instead echo=TRUE, what I get is the caption, then the codes, and then the graph, which is also not what I want. What I would like to show is the code for R, (and) the graph plotted with that R code, with the caption above the graph.

like image 814
Serena Avatar asked Jul 09 '14 15:07

Serena


1 Answers

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.

enter image description here

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

like image 182
Michael Harper Avatar answered Sep 21 '22 23:09

Michael Harper