How to make a figure caption in Rmarkdown? - knitr

I am thinking about writing my thesis with rmarkdown and latex. I'm getting the hang of how it all works, however, when I try to add a figure (not an R plot) to the text and render it to pdf, the caption and in-text reference dissappear.
This is the code snippet I use to add a figure:
---
title: "Untitled"
output: pdf_document
---
see figure \ref{fig1}.
![picture \label{fig1}](figure1.png)
This is what knitr creates:
This is what pandoc creates:
Question:
How do I make figure captions and in-text references to those figures in Rmarkdown that will display when rendered to pdf?
OR
How do I tell pandoc what Rmarkdown is so it will render R code and plots?

Please see the documentation of R Markdown for PDF output, and in particular, look for fig_caption. Figure captions are turned off by default in R Markdown, and you have to turn them on (fig_caption: true). You can also find this setting from the gear button on the toolbar of RStudio IDE.

Update: please check https://github.com/yihui/knitr/issues/1063.
Question: How do I make figure captions and in-text references to those figures in Rmarkdown that will display when rendered to pdf?
To get the cross-reference in the PDF produce by LaTeX you need to run LaTeX more than once. Some LaTeX IDE does it for you.
knitr is only running LaTeX once and that is the reason that you only get ??. To confirm that this was the problem I ran
library(knitr)
knitr()
in R that returned
see figure \ref{fig1}.
\begin{figure}[htbp]
\centering
\includegraphics{imagem.jpg}
\caption{picture \label{fig1}}
\end{figure}
which is a valid LaTeX code.
How do I tell pandoc what Rmarkdown is so it will render R code and plots?
Pandoc only understand Markdown (not RMarkdown). First you have to call knitr to generate the Markdown from the RMarkdown and after it call Pandoc to convert the Markdown to LaTeX.

I just found a very useful solution here.
First, include the following chunk:
```{r functions, include=FALSE}
# A function for captioning and referencing images
fig <- local({
i <- 0
ref <- list()
list(
cap=function(refName, text) {
i <<- i + 1
ref[[refName]] <<- i
paste("Figure ", i, ": ", text, sep="")
},
ref=function(refName) {
ref[[refName]]
})
})
```
After, we can add the caption of the figure/table in the figure chunk options like:
```{r, fig.cap=paste("Your caption.")}
See that fig.cap works better with paste.

In Rmarkdown
for markdown figures
![caption \label{labelx}](link_to_figure, or path of figure){figure dimensions}
# how to cite markdown figure
\ref{labelx}
for latex figures
Add following in the figure environment of latex which starts with
\begin{figure}
includegraphics[]{/path to figure}
\label{label}
\end{figure}
# how to cite latex
\ref{label}
for bookdown
add chunk names as label names like
{r label2,echo=F}
# to cite by using bookdown use
\#ref(fig:label2)
similarly for tab we cite table as \#ref(tab:table_label)
For captioner package
add a chunk at the top of rmarkdown document
tab_cap <- captioner(prefix = "table")
fig_cap <- captioner(prefix = "figure")
where prefix is the prefix for cross referencing a figure.
add this in chunk options
{r fig_cap("labelforcaptioner","caption for captioner figure"}
note that fig_cap is similar to fig_cap in chunk code for captioner.
and to cite use
`r fig_cap("label4",display='cite')

Related

Getting rid of figure captions under figures

This is for Papaja. How do I get rid of figure captions at the bottom of the figure. My figure caption is quite long and I am going to a figure list. Now, I get both, and the figure caption runs out on the bottom of the page. Thanks, Jeff
There are currently two options to accomodate long figure captions or tall figures. You can adjust the line spacing/font size or, as you are doing, use a separate list of figure captions. I'll briefly explain both approaches.
1. List of figure captions
a) The LaTeX way
You can suppress the captions (defined by the chunk option fig.cap) below all figures by adding the following to the YAML front matter:
figurelist: yes
header-includes:
- \captionsetup[figure]{textformat=empty}
b) The knitr way
If you would rather suppress figure captions only where necessary you can instead get knitr to do this.
Set the figure short caption via the chunk option fig.scap. To ensure that fig.scap takes effect, knitr requires that the chunk specifies out.width, out.height, or fig.align, as explained here. Remove the figure caption below the figure by setting fig.cap = " ".
Finally, I generally recommend to specify figure (and table) captions, especially long ones, using text references (e.g., (ref:reference-label). Taking all of this together, the following should do the trick:
(ref:figure-caption) This is a long figure caption!
```{r fig.cap = " ", fig.scap = "(ref:figure-caption)", out.width = "\\textwidth", fig.height = 7}
plot(cars)
```
Make sure that you include figurelist: yes in the YAML front matter and that you are using at least the development version of papaja with the commit hash d6227d8a750c6e67a323828a7cb0b8b8331aeac7, e.g. devtools::install_github("crsh/papaja#d6227d8a750c6e67a323828a7cb0b8b8331aeac7").
2. Adjust line spacing and font size
As mentioned in the manual, you can adjust the line spacing of figure captions. To additionally decrease the font size, add the following to the YAML front matter:
header-includes:
- \usepackage{setspace}
- \captionsetup[figure]{font={stretch=1,scriptsize}}
This should also make room for bigger captions or taller figures.

How can I stop org mode from moving my figures to the last page?

I'm currently trying to write up my thesis in emacs org-mode, and have run into some problems with file inclusions.
When I include figures with:
#+NAME: fig:banana
#+CAPTION: this is a figure caption
[[/path/to/image.png]]
(or using a pdf) it works fine. But when I insert another image, it is somehow moved to the end of the file instead of being inserted where it is called.
My pdf-export process (in my ~/.emacs file) looks like this:
(setq org-latex-pdf-process
'("latexmk -pdflatex='pdflatex -interaction nonstopmode' -pdf -bibtex -f %f"))
Any ideas on how to fix this?
A friend of mine pointed me to the LaTex package placeins.
#+LATEX_HEADER: \usepackage{placeins}
* section 1
** hi!
#+TITLE: fig:banana
#+CAPTION: this is a banana figure
[[/link/to/banana.png]]
\FloatBarrier
* section 2
The FloatBarrier stops floats (figures are floats) from jumping over them. I will need to look into passing [tbh] options to figures from org mode further.
Check the org-mode manual on how to pass placement options such as [h], [t] etc. to theLaTeX compiler.
If you're not sure how to control where figures (more precisely, floats) get placed by LaTeX, please refer to any introduction.
Or do you want the figure to be placed where you include it? If so, you might not need it to be a float.

how to highlight latex-syntax in org-mode but no effect on the produced PDF

I use org-mode+LaTex to take scientific notes and produce them to PDFs, I can use
#+BEGIN_src latex:
\begin{equation}
\int_\text{Birth}^{Death} work \mathrm{d} t = \text{LIFT}
\end{equation}
#+END_src
to highlight all latex codes between codes #+BEGIN_src latex .... #+END but if I don't delete this codes before I produce my org-document to PDF, I will get the unexpected #+BEGIN_src latex and #+END in the PDF.
Is there a more convenient way that can make latex syntax highlighted in org-mode with no unexpected codes left in PDF?
I searched some info about highlight source codes in org-mode, however, it seem no one concerns my demand that I simply only need the function of highlights of the latex syntax to make me edit easily, not the highlights in the resulting PDF.
Thanks a lot.
The (first?) problem is the colon after "latex" on the first line.

Emacs org-mode markdown export: #+TITLE option not exported

I use the great org-mode to easily push modifications of README.md to GitHub projects. Markdown export works great, except for the #+TITLE option not being exported to Markdown - which works flawlessly for HTML export.
I want to keep the file name README.org for convenient converting to Markdown, else I could have chosen the title as file name, which displays the title correctly on GitHub.
Any suggestions on how to achieve this?
Based on your question and subsequent comments, you seem to want to achieve three things:
Define a custom title that gets exported as a top-level headline.
Insert the TOC after the title.
The TOC should not include the title.
Custom location for TOC
Inserting the TOC at a custom location is easy, so let's start with that: Add
#+OPTIONS: toc:nil
to the export options at the top of README.org. By itself, this tells org-mode not to include the default TOC when exporting. You can then place the TOC where you want it to go by inserting
#+TOC: headlines
at the desired location. (This method is not specific to Markdown export.)
Custom title that doesn't show up in TOC
Defining a custom title that is not included in the TOC is a bit trickier, but the basic idea is to exclude the title from the TOC by formatting it as a Markdown headline instead of an org headline. As a first step, change README.org to look like this:
#+OPTIONS: toc:nil
# Emacs als Python-Power-Editor für den RasPi
#+TOC: headlines
* Wieso nur ausgerechnet Emacs???
...
Out of the box this won't yield the desired results because org will interpret the title as a comment and by default the Markdown exporter is configured to ignore comments. However, in order to change the default behavior you can
define a custom transcoder for comments in your .emacs:
(defun org-md-comment (comment contents info)
"Transcode COMMENT object into Markdown format.
CONTENTS is nil. INFO is a plist holding contextual information."
(format "# %s" (org-element-property :value comment)))
redefine the Markdown export backend to make use of this transcoder:
(org-export-define-derived-backend 'md 'html
;; ...
:translate-alist '((bold . org-md-bold)
(code . org-md-verbatim)
(comment . org-md-comment) ;; <--- Use custom transcoder
(comment-block . (lambda (&rest args) ""))
;; ...
))
The original definition of the backend can be found in the file ox-md.el; this file is located in the directory of your org-mode installation. You'll need to copy the full definition to your .emacs file and change the line
(comment . (lambda (&rest args) ""))
as shown above.
Results
With these customizations the resulting README.md file looks like this:
# Emacs als Python-Power-Editor für den RasPi
<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="text-table-of-contents">
<ul>
<li>1. Wieso nur ausgerechnet Emacs???</li>
<li>2. Die Maus ist tot, es leben die shortcuts!</li>
<li>3. Auf den Emacs, fertig, los!</li>
</ul>
</div>
</div>
# Wieso nur ausgerechnet Emacs???
...
See http://article.gmane.org/gmane.emacs.orgmode/82634.
The problem is supposed to be fixed. Only waiting for an update of the converter on GitHub site...
This is useful to get what the answer expects but I think it is not the right path to resolve this question. Let me explain it
I think the issue is about exporting options from org-mode to md but I also want to keep my docs in org-mode and this hacks org-mode export option adding another line for title exporting to md headline 1 but not manages the whole thing.
What I expect and I guess this is the important issue is to export orgmode to md properly, I mean:
the title from orgmode to md heading one (#) -as orgmode to html does.
the heading one from orgmode (*) to md heading two (##)
If this issue is not about it I should open a new one :)
Best!

LyX->Rnw conversion automatically inserts ligature breaks between repeated "<" characters

The title says it all; the screenshot below gives the gory details. (The .Rnw file in the temporary buffer folder is identical to the LaTeX Source in the image.) As you can imagine, knit() won't knit this crap. I cannot for the life of me figure out how to make those ligature breaks go away.
So I guess my question is... Help?
You probably did not read the manual, which has instructions on how to input R code in a LyX document: either through Insert --> TeX Code (Ctrl + L), or use the Chunk environment from the drop-down menu on the toolbar. You should not type R code as normal paragraphs in LyX.