Rmarkdown: cross-reference image included with markdown syntax - latex

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

Related

How to convert Rmarkdown file to working latex file

I have written a manuscript I would like to submit to a journal in Rmarkdown. The journal accepts word and latex files, so I am looking for a way to generate a working .tex file out of my .Rmd file.
I have read some posts that allude to this being possible (e.g., How to generate LaTeX file without preamble in R markdown?) and this is getting me some of the way, but I am still having problems.
For example, using the method mentioned in the post above, I can convert a test .Rmd into something with a .tex filetype. This is the test Rmarkdown (just the usual template for new files):
---
title: "Test document"
author: "Me"
date: "23 7 2020"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
This compiles fine to PDF as it should. Then, in the console I run:
knitr::knit("test.Rmd")
to get a markdown file test.md in my working directory, and then I can apparently convert this .md file to .tex with
rmarkdown::pandoc_convert("test.md", to = "latex", output = "test.tex")
This produces a .tex file that, when I double click on it, pops up a PDF view of the file that looks fine. Taking a look at the file though, it is incomplete or at least unfamiliar to me:
\hypertarget{r-markdown}{%
\subsection{R Markdown}\label{r-markdown}}
This is an R Markdown document. Markdown is a simple formatting syntax
for authoring HTML, PDF, and MS Word documents. For more details on
using R Markdown see \url{http://rmarkdown.rstudio.com}.
When you click the \textbf{Knit} button a document will be generated
that includes both content as well as the output of any embedded R code
chunks within the document. You can embed an R code chunk like this:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{summary}\NormalTok{(cars)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## speed dist
## Min. : 4.0 Min. : 2.00
## 1st Qu.:12.0 1st Qu.: 26.00
## Median :15.0 Median : 36.00
## Mean :15.4 Mean : 42.98
## 3rd Qu.:19.0 3rd Qu.: 56.00
## Max. :25.0 Max. :120.00
\end{verbatim}
\hypertarget{including-plots}{%
\subsection{Including Plots}\label{including-plots}}
You can also embed plots, for example:
\begin{figure}
\centering
\includegraphics{figure/pressure-1.png}
\caption{plot of chunk pressure}
\end{figure}
Note that the \texttt{echo\ =\ FALSE} parameter was added to the code
chunk to prevent printing of the R code that generated the plot.
As far as I can tell, it is missing the preamble, \begin{document}, \end{document}, and I have no idea what is going on with hypertarget bit of the section headers. Unsurprisingly, it does not "re-compile" when I hit run in MiKTeX. The verbatim bits for the code chunks look to be what I'm after, though.
So, is there a way to generate a .tex file that compiles out of an .Rmd file? Or will I have to manually write the preamble and all that? If the answer to my problem is "read up pandoc", then fair enough, I will have to bite the bullet and finally have a look at it. But I find it hard to imagine that there is no good (easy) way to prepare submittable manuscripts in Rmarkdown.
Pandoc generates LaTeX snippets by default, i.e., not a full document. This can be changed by calling pandoc with the --standalone option:
rmarkdown::pandoc_convert(
"test.md",
to = "latex",
output = "out.tex",
options = "--standalone"
)
You can let R do the work and shorten your commands to
render("test.Rmd", output_format = "latex_document")
A project of interest might be rticles.

How to typeset argmin and argmax in Markdown?

There are posts in TeX.SE that shows how argmin and argmax with limits can be typesetted using the \DeclareMathOperator* command. But how to do this in Markdown?
I am especially interested in doing this in Jupyter Notebook when I'm documenting in Markdown.
Is this possible?
The way to do this is by using the \underset command.
Syntax:
\underset{<constraints>}{\operatorname{<argmax or argmin>}}
Example:
$\underset{c\in C}{\operatorname{argmax}}$
Maybe this is what you look for
$ \hat{\theta}^{MLE}=\underset{a}{\operatorname{\argmax}} P(D|\theta) = \frac{a_1}{a_1+a_0} $
The trick is done by \underset, which put a character under an expression, as you see below.
Anyway, I see widely used the simple underscore expression, along with \argand \max, as you see below.
If you want to know something more about the many ways you can choose, take a look at here: Command for argmin or argmax?
Hope to be helpful
This worked for me when using pandoc for markdown-to-PDF conversion. (The subscript 'a' is correctly placed underneath the 'argmin'):
---
header-includes:
- \newcommand{\argmin}{\mathop{\mathrm{argmin}}\limits}
---
Some text.
$A = \argmin_a f(a)$

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

Pandoc generation of pdf from markdown 4th header is rendered differently

I am using pandoc to generate a pdf from some markdown. I am using h1 through h4 via hash symbols. Example h1=#, h4=####. When I generate my document like this:
pandoc input.md -o output.pdf
I get a document where h1, h2 and h3 have a newline after them but h4 does not have a new line. The text starts on the same line as the header (it isn't formatted the same way, but there isn't a newline character between).
I've tried adding spaces after the #### and adding manual line returns using my editor but nothing seems to work.
Any ideas?
While the mentioned solutions work fine, pandoc offers a build-in variable to enable block-headings for \paragraph.
pandoc -s -o out.pdf some.md -V block-headings
Pandoc Manual
pandoc generates PDFs via LaTeX. In LaTeX, "headers" are generated using the following commands:
\section
\subsection
\subsubsection
\paragraph
\subparagraph
As you can see, a "level four heading" corresponds to the \paragraph command, which is rendered as you describe. There simply isn't a \subsubsubsection command to use.
The only way to get what you want is to redefine the \paragraph command, which is quite tricky. I haven't been able to make it work with Pandoc.
While #tarleb’s answer is surely the best (except that it specifies a
wrong amount of vertical space), here is a “simpler” (by some measure)
but more hacky (in LaTeX terms at least) solution which optionally uses a Pandoc Lua filter or a LaTeX hack but avoids loading another LaTeX package.
We want the LaTeX source to look something like this:
\hypertarget{level-4-heading}{%
\paragraph{Level 4 heading}\label{level-4-heading}}
\hfill
Lorem ipsum dolor sit amet.
This LaTeX looks awful, but if you don’t need to keep or share the LaTeX
source it does what you probably want: a space between the level 4
heading and the paragraph after it equal to the space between a level 3
heading and the paragraph after it.
Here is how it works: since a \hfill on a line on its own is about as
close as you can get to an empty paragraph in LaTeX you get a first
paragraph — the one running in with the heading — containing only
horizontal white space until the end of the line, and then immediately
after a new paragraph — the actual first paragraph after the heading —
with just a normal paragraph space between it and the heading. This
probably also upsets LaTeX’s idea about what a \paragraph should be
like as little as possible.
The “manual” way to do this is as follows:
#### Level 4 heading
````{=latex}
\hfill
````
Lorem ipsum dolor sit amet.
This uses Pandoc’s relatively new raw markup syntax — the “code block”
is actually a raw LaTeX block — but it looks even more awful than the
resulting LaTeX source! It is also a tedious chore to have to insert
this after every level 4 heading. In other words you want to insert that
raw LaTeX automatically, and that can be done with a Lua filter:
--[======================================================================[
latex-h4-break.lua - Pandoc filter to get break after a level 4 heading.
Usage:
$ pandoc --lua-filter latex-h4-break.lua input.md -o output.pdf
--]======================================================================]
-- create it once, use it many times!
local hfill_block = pandoc.RawBlock('latex', '\\hfill')
function Header (elem)
if 4 == elem.level then
return { elem, hfill_block }
else -- ignore headings at other levels!
return nil
end
end
However you can also do a simple LaTeX hack in a header-includes
metadata block to get the same effect:
---
header-includes:
- |
``` {=latex}
\let\originAlParaGraph\paragraph
\renewcommand{\paragraph}[1]{\originAlParaGraph{#1} \hfill}
```
---
#### Level 4 heading
Lorem ipsum dolor sit amet.
This works by first creating an “alias” of the \paragraph command and
then redefining the \paragraph command itself, using the alias in the
new definition so that now wherever the LaTeX source created by Pandoc
contains \paragraph{Foo} it is if it instead had contained
\paragraph{Foo} \hfill which does what we want with zero extra
dependencies! (In case you wonder the wacky spelling of the “aliased”
command is to minimize the risk that it collides with anything which
already exists, since the TeX \let command doesn’t check for that. We
certainly don’t want to overwrite any existing command!)
NOTE: If you really should want more or less space than a normal
paragraph break after the heading just add an appropriate \vspace
command after the \hfill: \hfill \vspace{-0.5\parskip}.
Shifting Headers
Arguably the best way to solve this would be to avoid the problem altogether by shifting what a level 4 header corresponds to. The default for pandoc is to use \section commands for 1st level and \paragraph for 4th level headers. This can be altered via the --top-level-division parameter:
--top-level-division=[default|section|chapter|part]
Treat top-level headers as the given division type in LaTeX [...] output. The hierarchy order is part, chapter, then section; all headers are shifted such that the top-level header becomes the specified type. The default behavior is to determine the best division type via heuristics [...]
So with --top-level-division=chapter, a 4th-level header would be generated via the \subsubsection command.
Styling via LaTeX
If this is not an option, the next best way is to configure the layout of the corresponding LaTeX command: for level-four headers, this is \paragraph by default. The following methods are taken from TeX StackExchange answers.
Please also check the answer by bpj, which is much simpler than what's proposed below.
Default document-classes
The default way would be to configure \paragraph via the titlesec package. We can use the header-includes metadata field for this, which pandoc will include in the intermediate LaTeX document.
---
header-includes: |
``` {=latex}
\usepackage{titlesec}
\titlespacing*{\paragraph}{0pt}{1ex}{-\parskip}
\titleformat{\paragraph}[hang]
{\normalfont\bfseries}
{}
{0pt}
{}
```
---
KOMA document-classes
Using titlesec won't work properly for documents using KOMA classes (like scrartcl), as KOMA has it's own ways of doing things. For these, use this alternative snippet:
---
documentclass: scrartcl
header-includes: |
``` {=latex}
\makeatletter
\renewcommand\paragraph{\#startsection{paragraph}{4}{\z#}%
{-3.25ex \#plus -1ex \#minus -0.2ex}%
{0.01pt}%
{\raggedsection\normalfont\sectfont\nobreak\size#paragraph}%
}
\makeatother
```
---
I am not sure, why, but this works for me:
Put $\ \\ $ in the first line after your #### headline

Inserting code in this LaTeX document with indentation

How do I insert code into a LaTeX document? Is there something like:
\begin{code}## Heading ##
...
\end{code}
The only thing that I really need is indentation and a fixed width font. Syntax highlighting could be nice although it is definitely not required.
Use listings package.
Simple configuration for LaTeX header (before \begin{document}):
\usepackage{listings}
\usepackage{color}
\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
\lstset{frame=tb,
language=Java,
aboveskip=3mm,
belowskip=3mm,
showstringspaces=false,
columns=flexible,
basicstyle={\small\ttfamily},
numbers=none,
numberstyle=\tiny\color{gray},
keywordstyle=\color{blue},
commentstyle=\color{dkgreen},
stringstyle=\color{mauve},
breaklines=true,
breakatwhitespace=true,
tabsize=3
}
You can change default language in the middle of document with \lstset{language=Java}.
Example of usage in the document:
\begin{lstlisting}
// Hello.java
import javax.swing.JApplet;
import java.awt.Graphics;
public class Hello extends JApplet {
public void paintComponent(Graphics g) {
g.drawString("Hello, world!", 65, 95);
}
}
\end{lstlisting}
Here's the result:
You could also use the verbatim environment
\begin{verbatim}
your
code
example
\end{verbatim}
Here is how to add inline code:
You can add inline code with {\tt code } or \texttt{ code }. If you want to format the inline code, then it would be best to make your own command
\newcommand{\code}[1]{\texttt{#1}}
Also, note that code blocks can be loaded from other files with
\lstinputlisting[breaklines]{source.c}
breaklines isn't required, but I find it useful. Be aware that you'll have to specify \usepackage{ listings } for this one.
Update: The listings package also includes the \lstinline command, which has the same syntax highlighting features as the \lstlisting and \lstinputlisting commands (see Cloudanger's answer for configuration details). As mentioned in a few other answers, there's also the minted package, which provides the \mintinline command. Like \lstinline, \mintinline provides the same syntax highlighting as a regular minted code block:
\documentclass{article}
\usepackage{minted}
\begin{document}
This is a sentence with \mintinline{python}{def inlineCode(a="ipsum)}
\end{document}
Specialized packages such as minted, which relies on Pygments to do the formatting, offer various advantages over the listings package. To quote from the minted manual,
Pygments provides far superior syntax highlighting compared to conventional packages. For example, listings basically only highlights strings, comments and keywords. Pygments, on the other hand, can be completely customized to highlight any token kind the source language might support. This might include special formatting sequences inside strings, numbers, different kinds of identifiers and exotic constructs such as HTML tags.
Minted, whether from GitHub or CTAN, the Comprehensive TeX Archive Network, works in Overleaf, TeX Live and MiKTeX.
It requires the installation of the Python package Pygments; this is explained in the documentation in either source above. Although Pygments brands itself as a Python syntax highlighter, Minted guarantees the coverage of hundreds of other languages.
Example:
\documentclass{article}
\usepackage{minted}
\begin{document}
\begin{minted}[mathescape, linenos]{python}
# Note: $\pi=\lim_{n\to\infty}\frac{P_n}{d}$
title = "Hello World"
sum = 0
for i in range(10):
sum += i
\end{minted}
\end{document}
Output:
Use Minted.
It's a package that facilitates expressive syntax highlighting in LaTeX using the powerful Pygments library. The package also provides options to customize the highlighted source code output using fancyvrb.
It's much more evolved and customizable than any other package!
A very simple way if your code is in Python, where I didn't have to install a Python package, is the following:
\documentclass[11pt]{article}
\usepackage{pythonhighlight}
\begin{document}
The following is some Python code
\begin{python}
# A comment
x = [5, 7, 10]
y = 0
for num in x:
y += num
print(y)
\end{python}
\end{document}
which looks like:
Unfortunately, this only works for Python.
Since it wasn't yet mentioned here, it may be worth to add one more option, package spverbatim (no syntax highlighting):
\documentclass{article}
\usepackage{spverbatim}
\begin{document}
\begin{spverbatim}
Your code here
\end{spverbatim}
\end{document}
Also, if syntax highlighting is not required, package alltt:
\documentclass{article}
\usepackage{alltt}
\begin{document}
\begin{alltt}
Your code here
\end{alltt}
\end{document}
Use Pygments !

Resources