How to cite within a figure caption w/ rmarkdown native citation?
Asked Answered
E

3

7

In R Markdown, I want a figure caption with a linked citation in R Markdown native citation style [@ref]. However, when I insert the [@hawking_thermodynamics_1983] snippet at the end into the caption, it's throwing just an error:

! Missing $ inserted.
<inserted text> 
                $
l.94 ...iontextfoo [@hawking_thermodynamics_1983]}

pandoc.exe: Error producing PDF
Error: pandoc document conversion failed with error 43

Example:

This is my code:

---
title: "Untitled"
author: "Author"
output: pdf_document
# bibliography: bibliography.bib
references:
- id: hawking_thermodynamics_1983
  author:
  - family: Hawking
    given: S. W.
  - family: Page
    given: Don. N.
  publisher: Communications in Mathematical Physics
  title: Thermodynamics of Black Holes in Anti-de Sitter Space.
  volume: 87
  type: article-journal
  issued:
    year: 1983
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

\begin{figure}[h]
\centering
\includegraphics[width=13cm]{example.jpg}
\caption{Captiontextfoo}\label{fig1}
\end{figure}

[@hawking_thermodynamics_1983]

# Bibliography

with this output:

enter image description here

I want the citation in parentheses to appear inside the figure caption, with working link to the bibliography. The bibliography should appear automatically as usual.

How could I possibly achieve this?


Notes:

  • I also tried \[@... or w/o brackets but didn't work.
  • I tried also this \caption{Captiontextfoo \cite{[@hawking_thermodynamics_1983]}} from this answer, but didn't work as well, shows only [?].
  • R version 3.4.3 (2017-11-30)
  • Platform: x86_64-w64-mingw32/x64 (64-bit)
  • Running under: Windows 7 x64 (build 7601) Service Pack 1
Envoi answered 17/12, 2017 at 23:16 Comment(1)
not sure about r-markdown, but in plain pandoc ships with pandoc-citeproc built-in. you seem to use that syntax...Colotomy
A
7

This problem appears to be fixed, and the citation can be included directly within the fig.cap argument:

Here is a minimal example which creates an bib.bib file in the same directory as the .Rmd file. It also includes the graphic using includes_graphics:

---
output: pdf_document
bibliography: bib.bib
---

```{r setup, include=FALSE}
knitr::write_bib(x = "rmarkdown", file = "bib.bib")
```

```{r, echo = FALSE, fig.cap = "A plot [@R-rmarkdown]"}
plot(cars)
```

enter image description here

If this doesn't work (not entirely sure why it doesn't, but some people seem to have problems with the above), you can use text references (see Section 2.2.4 of the bookdown book).

(ref:caption) A plot [@R-rmarkdown]

```{r echo=FALSE, fig.cap="(ref:caption)"}
plot(cars)
```
Atoll answered 9/8, 2018 at 15:46 Comment(1)
I was still having this problem, but your idea of text references worked.Bamboozle
P
1

When I tried the example of Michael Harper above, the bibliographic reference worked fine. When I changed the plot to knitr::include_graphics('myfig.jpg') it didn't work and the caption just printed ...[@R-markdown].

I then did both a plot(...) and knitr::include_graphics('myfig.jpg'), and when I knitted to .pdf the caption for the plot(...) figure was correct while the same caption for the knitr::include_graphics('myfig.jpg') had ...[@R-markdown].

So there appears to be something about loading an external figure using knitr::include_graphics('myfig.jpg') that breaks the bibliographic reference in a latex/pdf output. It's fine for .html or .docx - the reference is correct.

---
output: pdf_document
bibliography: bib.bib
---
  
```{r setup, include=FALSE}
knitr::write_bib(x = "rmarkdown", file = "bib.bib")
```   
```{r, echo=F, fig.cap="Soil profile [@R-rmarkdown]"}
plot(cars)
knitr::include_graphics('SoilProfile-Haven-1.jpg',dpi=400)
```

enter image description here

Phloem answered 21/4, 2022 at 17:4 Comment(0)
H
-1

If you are only producing pdf output, you could use latex directly. Here is a minimal reproducible example:

biblio.bib

@Book{xie2015,
  title = {Dynamic Documents with {R} and knitr},
  author = {Yihui Xie},
  publisher = {Chapman and Hall/CRC},
  address = {Boca Raton, Florida},
  year = {2015},
  edition = {2nd},
  note = {ISBN 978-1498716963},
  url = {http://yihui.name/knitr/},
}

rmarkdown.Rmd

---
output: 
  bookdown::pdf_document2:
    citation_package: natbib
    toc: false
bibliography: biblio.bib
biblio-style: apalike
link-citations: yes
---

```{r nice-fig, fig.cap='Here is a nice figure! \\citep{xie2015}', out.width='80%', fig.asp=.75, fig.align='center', echo=FALSE}
par(mar = c(4, 4, .1, .1))
plot(pressure, type = 'b', pch = 19)
```

Produces:

enter image description here

Hopefully when the rmarkdown / pandoc dust settles in the near future, the original solution below will work with the latest releases once again.

Original

If you use the bookdown::pdf_document2 output format, there are enhanced cross-referencing features. Placing your figure inside a code chunk also makes it easier to output as html if you choose multiple output formats.

---
title: "Untitled"
author: "Author"
output: bookdown::pdf_document2
# bibliography: bibliography.bib
references:
- id: hawking_thermodynamics_1983
  author:
  - family: Hawking
    given: S. W.
  - family: Page
    given: Don. N.
  publisher: Communications in Mathematical Physics
  title: Thermodynamics of Black Holes in Anti-de Sitter Space.
  volume: 87
  type: article-journal
  issued:
    year: 1983
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

# R Markdown

```{r fig1, out.width='13cm', fig.cap='Captiontextfoo [@hawking_thermodynamics_1983]', echo=FALSE}
knitr::include_graphics("example.jpg")
```

# Bibliography

For the complete package documentation, see here. Also, note this closed Github issue demonstrating your requested output.

Session Info

sessionInfo()

# R version 3.4.3 (2017-11-30)
# Platform: x86_64-w64-mingw32/x64 (64-bit)
# Running under: Windows >= 8 x64 (build 9200)
# 
# Matrix products: default
# 
# locale:
# [1] LC_COLLATE=English_Australia.1252  LC_CTYPE=English_Australia.1252
# [3] LC_MONETARY=English_Australia.1252 LC_NUMERIC=C
# [5] LC_TIME=English_Australia.1252
# 
# attached base packages:
# [1] stats     graphics  grDevices utils     datasets  methods   base
# 
# loaded via a namespace (and not attached):
#  [1] compiler_3.4.3  backports_1.1.2 bookdown_0.5    magrittr_1.5    rprojroot_1.3-1
#  [6] htmltools_0.3.6 tools_3.4.3     yaml_2.1.16     Rcpp_0.12.14    stringi_1.1.6
# [11] rmarkdown_1.8   knitr_1.17      stringr_1.2.0   digest_0.6.13   evaluate_0.10.1
Homeo answered 18/12, 2017 at 0:8 Comment(7)
Promising, but throws Collected error summary (may duplicate other messages): pdflatex: Command for 'pdflatex' gave return code 1 Refer to 'test71.log' for details Latexmk: Use the -f option to force complete processing, unless error was exceeding maximum runs of latex/pdflatex. ! Missing $ inserted. <inserted text> $ l.111 ...ontextfoo [@hawking_thermodynamics_1983]} \label{fig:fig1} w/ your code, I updated my MiKTeX to 2.9.6500.and installed grom github devtools::install_github('rstudio/bookdown').Envoi
@jaySf, I couldn't replicate your error until I used a fresh environment, seems you may be caught up in the rmarkdown and pandoc bugs affecting the latest releases as a result of the pandoc 2 release. You may be better not to use the development versions until they have these squashed, although this blog posts suggests they are at least part way there.Homeo
Sorry, there was no space to be clear enough. I meant I took a look into Github link in your answer. After your code didn't work w/ bookdown standard version I tried the dev, but no change. I'm using old pandoc version 1.19.2.1 as well and rmarkdown 1.8. I rolled back now to bookdown 0.5, but your provided code seems still not to be working. Where could be the difference in our environments?Envoi
Not working for me, produces (?) rather than (Xie, 2015) in caption.Envoi
@jaySf, I cannot replicate your problem in a fresh session, my sessionInfo added to my answer.Homeo
I compared both session infos, updated some packages accordingly, but still not working. I added the error message to my question. Which pandoc version do you use? On my machine rmarkdown::pandoc_version() yields 1.19.2.1.Envoi
@jaySf, I'm using the version packaged with RStudio, which happens to be the same, 1.19.2.1.Homeo

© 2022 - 2024 — McMap. All rights reserved.