Caption above figure using knitr (LaTeX/PDF) - latex

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.

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.

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}

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)

Add a new block below it, with the same name, to print the code.
\documentclass{article}
\begin{document}
\begin{figure}
\caption{This is a caption above the figure}
<<a-plot, echo=FALSE>>=
plot(1)
#
\end{figure}
<<a-plot,echo=TRUE>>=
#
\end{document}

Related

Rmarkdown: cross-reference image included with markdown syntax

I would like to cross-reference an image which I include with the markdown ![caption with spaces](path/to/image.png) syntax.
I would like to be able to cross-reference this image as \#ref(fig:caption-with-spaces).
I am using bookdown::pdf_document2.
Is this possible?
Labels can be attached to images included in markdown using the syntax ![caption](path/to/image){#fig:anchor_name}.
That said, there are two further options
Use LaTeX's \includegraphics command.
Use knitr's include_graphics function.
A LaTeX solution would look something like:
\begin{figure}
\includegraphics{path/to/picture.png}
\caption{Caption with spaces}
\label{fig:example}
\end{figure}
A knitr solution would look like
```{r, fig.cap = "Caption with spaces", label="example"}
knitr::include_graphics("path/to/picture.png")
```
With both of these solutions you can cross-reference the resulting image with \ref{fig:example}.
R Markdown adds a figure ID when generating figures via R, but not for pure Markdown images. In this case, you can add an ID yourself:
![Caption with spaces](path/to/pictures.png){#fig:caption-with-spaces}
The id can be chosen freely, but should start with fig:.
If you'd like a keep everything in pure Markdown, but don't want to add identifiers manually, you can use a pandoc Lua filter:
local stringify = (require 'pandoc.utils').stringify
function Image (img)
if img.identifier == '' then
img.identifier = 'fig:' .. stringify(img.caption):gsub('%s', '-'):lower()
return img
end
end
Use by adding a pandoc_args parameter to your output settings:
output:
bookdown::pdf_document2:
pandoc_args: ['--lua-filter', 'auto-image-ids.lua']
You can add an image with R as:
{r schematic, echo=FALSE, fig.cap="Diseño de circuito esquemático", fig.align="center"}
knitr::include_graphics("schematic.png")
Then to reference the image:
\ref{fig:schematic}
Note: I tried other ways to reference the image like \#ref(fig:schematic) but this did not work for me

\afterpage and \endfloat

How do I combine \afterpage and \endfloat to easily switch between having figures and tables at the end of the document or having them in the text?
I want to easily choose between my figures at the end of the document and my figures in the text. Because of that, sometimes I will use \afterpage package and other times I will use \endfloat would be nice to combine both.
Right now, all the times I try to run \endfloat when I have a clear page, I get the following message:
Argument of \efloat#xfloat has an extra }.
I already tried to include after page in the DeclareDelayedFloatFlavor, something like:
\DeclareDelayedFloatFlavor{afterpage}{figure}
It did not work.
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{float}
\usepackage{afterpage}
% ---------------------
%figures at the end
% ---------------------
\usepackage[nolists]{endfloat}
% force landscape at the end
\begin{document}
{\afterpage{
\begin{figure}
\end{figure}
}
\end{document}
If you want to switch between having figures within the text and at the end, I suggest to only use the endfloat package. Commenting or commenting it's optional argument disable will allow you to quickly alternate between figures at the end or in the text.
I'm not entirely certain what the purpose of afterpage was in your example, but if you used it to move the figure to a separate page, this can conveniently be done with the p floating specifier.
\documentclass{article}
\usepackage[
disable
]{endfloat}
\begin{document}
test
\begin{figure}[p]
xxx
\caption{caption}
\end{figure}
test
\end{document}

How to implement full LaTeX syntax in Rmarkdown?

I have a two part question regarding the use of LaTeX in Rmarkdown:
1) When working in Rmarkdown (with the intent to render to PDF), is there a rule for when we should just use the double dollar signs ($$) to write something in LaTeX or when we should use the LaTeX syntax to begin and end all of our LaTeX code (e.g. \documentclass{...}, \begin{document}, \end{document}, etc.
I believe I have read that it is okay to just use the latter option, and Rmarkdown will ignore all of the escaped latex commands if the document is rendered to anything other than PDF.
2) The reason I am asking, in this case, is that I am trying to incorporate some labelled matrix multiplication in an Rmarkdown document I am writing. Specifically, I would like to include some matrices that take the form show on this page. Here is the code:
\documentclass{article}
\usepackage{amsmath}
\newenvironment{spmatrix}[1]
{\def\mysubscript{#1}\mathop\bgroup\begin{pmatrix}}
{\end{pmatrix}\egroup_{\textstyle\mathstrut\mysubscript}}
\begin{document}
\begin{equation}
\begin{spmatrix}{A}
a & b \\
c & d
\end{spmatrix}
\begin{spmatrix}{x}
x_1 \\
x_2
\end{spmatrix}
=
\begin{spmatrix}{b}
b_1 \\
b_2
\end{spmatrix}
\end{equation}
\end{document}
How would one implement this code in Rmarkdown? Do you need to move the \usepackage call into the YAML as suggested in other threads discussing the loading of LaTeX packages in Rmarkdown? Is the first line, \documentclass{article} even needed within an Rmarkdown document?
I'm new to all of this, and thusfar, I've been able to get by using the double dollar signs to set off all my LaTeX code for simple equations and even a simple matrix here and there that I've tried to write, but for mathematical expressions that require more formatting, aligning, multi-line proofs, etc., most of the examples I've encountered are on the TEX boards written with syntax similar to the code above. I haven't been able to figure out how to implement these types of examples in Rmarkdown. Any helpful suggestions or pointers where to better understand this issue would be much appreciated!
It is indeed possible to put most body-level LaTeX constructs into the body of your Rmd file. Other backends will ignore these constructs, but the result might look change. So from my point of view your are binding yourself to PDF output. But that might be fine in your case.
Concerning your concrete problem:
amsmath is already included by the default template, which also takes care of \ḑocumentclass and the document environment.
You need to add the environment definition into a separate tex file (in my case preamble.tex) and include that file via the YAML headers.
You can then use the LaTeX constructs as is in the Rmd body.
Putting things together:
---
output:
pdf_document:
keep_tex: yes
includes:
in_header: preamble.tex
---
\begin{equation}
\begin{spmatrix}{A}
a & b \\
c & d
\end{spmatrix}
\begin{spmatrix}{x}
x_1 \\
x_2
\end{spmatrix}
=
\begin{spmatrix}{b}
b_1 \\
b_2
\end{spmatrix}
\end{equation}

How to create a white-on-black style for LaTeX listings

I've been looking at Philip Bunge's post on how to create a "Tango" style with LaTeX listings, and trying to adapt this to make the default text style white and the background black (this is for slides, not an article!). This is what I added:
\definecolor{Black}{gray}{0.0}
\definecolor{White}{gray}{0.9}
...
\lstset{
basicstyle=\color{White},
backgroundcolor=\color{Black},
...
}
This assumes that basicstyle sets the default style of all text. The listings documentation says this:
basicstyle is selected at the beginning of each listing. You could use \footnotesize,
\small, \itshape, \ttfamily, or something like that. The last token of must not read any following characters.
The output of this still shows "default" text as black. It is possible to set more style directives that cover most tokens in a given programming language, but even doing this some tokens (such as brackets and other punctuation) will be missed. What did I do wrong?
The following code worked for me, but I converted the .dvi file to a .pdf in order to have the text appear as white, so it might have been your viewer? I'm using xdvi and xpdf.
\documentclass[a4paper, 11pt]{article}
\usepackage{listings}
\usepackage{color}
\definecolor{theWhite}{gray}{0.9}
\definecolor{theBlack}{gray}{0.0}
\lstset { basicstyle=\color{theWhite}, backgroundcolor=\color{theBlack} }
\begin{document}
\begin{lstlisting}
((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))
\end{lstlisting}
\end{document}
I hope that helps!

Adding a caption to an equation in LaTeX

Well, it seems simple enough, but I can't find a way to add a caption to an equation.
The caption is needed to explain the variables used in the equation, so some kind of table-like structure to keep it all aligned and pretty would be great.
The \caption command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:
\begin{figure}
\[ E = m c^2 \]
\caption{A famous equation}
\end{figure}
The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof command of the caption package can be used to place a caption outside of a floating environment. It is used like this:
\[ E = m c^2 \]
\captionof{figure}{A famous equation}
This will also produce an entry for the \listoffigures, if your document has one.
To align parts of an equation, take a look at the eqnarray environment, or some of the environments of the amsmath package: align, gather, multiline,...
You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat
I say this because captions are usually applied to floats.
Straight ahead equations (those written with $ ... $, $$ ... $$, begin{equation}...) are in-line objects that do not support \caption.
This can be done using the following snippet just before \begin{document}
\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}
\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
\let\ORIGINALcaption\caption
\def\caption{%
\addtocounter{equation}{-1}%
\ORIGINALcaption
}%
\ORGeqfloat
}
and when adding an equation use something like
\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}
As in this forum post by Gonzalo Medina, a third way may be:
\documentclass{article}
\usepackage{caption}
\DeclareCaptionType{equ}[][]
%\captionsetup[equ]{labelformat=empty}
\begin{document}
Some text
\begin{equ}[!ht]
\begin{equation}
a=b+c
\end{equation}
\caption{Caption of the equation}
\end{equ}
Some other text
\end{document}
More details of the commands used from package caption: here.
A screenshot of the output of the above code:

Resources