Search code examples
latexknitrcaptiontexmaker

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.


Solution

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

    enter image description here