The caption above the picture using knitr (LaTeX / PDF)

I would like to place an inscription over the figure using knitr in texmaker. I know this question has already been asked , and I understand that the proposed solution is to use:

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

But this way I can not show the code (with echo=FALSE ). And if I choose echo=TRUE instead, then I get the header, 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 constructed with this R code, with an inscription above the graph.

+6
source share
3 answers

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

+2
source

I prefer to use LaTeX packages for a configuration similar to this: Tex StackExchange has a large community that has developed methods for loading such issues.

The floatrow package can be used to change the title above the picture. This is pretty much based on this previous answer .

Using R Markdown, since this is the most commonly used workflow these days, the package can be downloaded by including the header-includes include argument in YAML, as shown below:

 --- 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, first the code is displayed, then the signature and the schedule.

enter image description here

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

+4
source

This is a small modified version of kohske's answer, which includes \begin{figure} and adds \label . Please note that it contains 5 lines, and 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) 
+1
source

All Articles