Evaluate inline r code in rmarkdown figure caption
knitr
evaluates chunk options as R code. Therefore, to include a variable value in a figure caption, just compose the required string using paste
or sprintf
:
fig.cap = paste("Graph of", nrow(data), "data points")
Note that this might be problematic if data
is created inside this chunk (and not in a previous chunk) because by default chunk options are evaluated before the chunk itself is evaluated.
To solve this issue, use the package option eval.after
to have the option fig.cap
be evaluated after the chunk itself has been evaluated:
library(knitr)
opts_knit$set(eval.after = "fig.cap")
Here a complete example:
---
title: "SO"
output:
word_document:
fig_caption: yes
---
```{r fig.cap = paste("Graph of", nrow(iris), "data points.")}
plot(iris)
```
```{r setup}
library(knitr)
opts_knit$set(eval.after = "fig.cap")
```
```{r fig.cap = paste("Graph of", nrow(data2), "data points.")}
data2 <- data.frame(1:10)
plot(data2)
```
The first figure caption works even without eval.after
because the iris
dataset is always available (as long as datasets
has been attached). Generating the second figure caption would fail without eval.after
because data2
does not exist before the last chunk has been evaluated.
How to get a newline in a figure caption in Rmarkdown bookdown pdf:document2
Instead of a newline, you may consider using sub-figures, e.g.
---
title: "MRR captions"
author: "Susannah Cowtan"
date: "14 December 2018"
output:
bookdown::pdf_document2:
keep_tex: true
header-includes:
- \usepackage{subfig}
---
See Figure \@ref(fig:plot-cars), which contains Figure \@ref(fig:plot-cars1) and Figure \@ref(fig:plot-cars2).
```{r plot-cars, fig.height = 3, fig.width = 4,, out.width='49%', fig.cap='Two plots', fig.subcap = c('foo bar baz', 'foobar')}
plot(mpg ~ wt, data = mtcars)
plot(cars)
```
Rmarkdown figure caption not printing correctly
It seems like a code chunk problem. Try this:
```{r top_3pt_scorers, echo = FALSE}
top_3pt_shooters <- NBAdf %>%
filter(PTS_TYPE == 3) %>%
group_by(PLAYER_NAME) %>%
dplyr::summarize(Threes_attempted = n(), Threes_made = sum(as.numeric(FGM)),
Three_point_total = sum(PTS, na.rm = TRUE))
knitr::kable(head(top_3pt_shooters[order(top_3pt_shooters$Threes_made, decreasing = TRUE), ]),
caption = "The top 3 point scorers in the NBA")
```
You may use fig_caption = TRUE
in your YAML header.
This may help you:
---
title: "Caption"
author: "bttomio"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
pdf_document:
fig_caption: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(kableExtra)
```
## Caption with kable
```{r dt}
dt <- mtcars[1:5, 1:6]
kbl(dt, caption = "Demo table", booktabs = T) %>%
kable_styling(latex_options =c("striped", "hold_position"))
```
```{r dt2}
dt <- mtcars[1:5, 1:6]
kbl(dt, caption = "Same demo table", booktabs = T) %>%
kable_styling(latex_options =c("striped", "hold_position"))
```
-output
r/rmarkdown/knitr: How to add an evaluate r chunk to a figure legend?
from http://yihui.name/knitr/options/ by @Yihui:
eval.after: (fig.cap) a character vector of option names; these
options will be evaluated after a chunk is evaluated, and all other
options will be evaluated before a chunk (e.g. for chunk option
fig.cap=paste('p-value is', t.test(x)$p.value), it will be evaluated
after the chunk according to the value of x if eval.after='fig.cap')
In short, to make your paste
work, use eval.after='fig.cap'
like this
---
title: "Untitled"
author: "chinsoon12"
date: "April 21, 2016"
output:
html_document:
fig_caption: true
---
```{r, echo=FALSE}
A <- "A"
B <- "B"
```
```{r pressure, echo=FALSE, eval.after='fig.cap', fig.cap=paste("This is my caption", A)}
A <- "A"
B <- "B"
plot(cars)
```
You might also want to check out these:
- Inserting Captions and Cross References in a R Markdown Document by Andy Lyons
- Figure and Table Captions in Markdown by fishR Blog
Print RMarkdown captions from a loop
It seems that knitr
is smart enough to do the task automatically. By adding names(mtcars)
to the figure caption, knitr iterates through these in turn to produce the correct caption. The only problem now is how to stop all of the list indexes from printing in the document...
---
title: "Caption loop"
output: pdf_document
---
```{r loops, fig.cap=paste("Graph of mpg vs.", names(mtcars)), message=FALSE, echo=FALSE, warning=FALSE}
library(tidyverse)
map(
names(mtcars),
~ ggplot(mtcars) +
geom_point(aes_string(x = 'mpg', y = .))
)
```
Knitr and Figure Caption in HTML
You can set eval.after="fig.cap"
so that figure captions are evaluated after the chunk is run. That way, you can define your captions inside the chunk.
---
title: "Caption Test"
author: "Some Author"
date: "February 18, 2016"
output: html_document
---
```{r}
library(ggplot2)
library(knitr)
opts_knit$set(eval.after = 'fig.cap')
```
```{r, fig.cap = cap}
## Plot 1
qplot(carat, price, data = diamonds)
cap <- "This is caption 1"
## Plot 2
qplot(carat, depth, data = diamonds)
cap <- c(cap, "This is caption 2")
```
knitr/Rmarkdown: Figures side-by-side with a single caption
its both possible in knitr or plain latex.
in knitr set the chunk option to:
echo=FALSE,out.width="49%",out.height="49%",fig.show='hold',
fig.align='center'
I used the latex package subcaption,
imported in the header-includes section of the YAML header.
---
title: "Untitled"
author: "V"
date: "22 4 2020"
output: pdf_document
header-includes:
- \usepackage{subcaption}
---
# add Two figures with latex
\begin{figure}[h]
\begin{subfigure}{.5\textwidth}
\includegraphics[]{CAT.png}
\end{subfigure}%
\begin{subfigure}{.5\textwidth}
\includegraphics[]{CAT.png}
\end{subfigure}
\caption{This is the main caption - Years 2020 - 2030 - the main caption. }
\end{figure}
# add Two figures with Knitr
```{r, echo=FALSE,out.width="49%",out.height="49%",fig.show='hold',
fig.align='center', fig.cap="This is the main caption - Years 2020 - 2030 - the main caption."}
knitr::include_graphics(c("CAT.png","CAT.png"))
knitr: Use an inline expression in fig.cap chunk option
fig.cap
is evaluated as an R expression, so instead of using \rinline
(and thus having the caption again parsed by knitr
), you can just create the caption string in R.
%% begin.rcode fig.cap=paste("x is", x)
but because fig.cap
is evaluated before x
is created by default, you will need to postpone the evaluation of fig.cap
; to do that, you can include a chunk like this in the beginning of your document:
%% begin.rcode setup, include=FALSE
%% opts_knit$set(eval.after = 'fig.cap')
%% end.rcode
It specifies fig.cap
to be evaluated after the code chunk is evaluated, i.e. when x
is available for you to use in the figure caption. See eval.after
in the documentation.
The other way to do this is to create x
in a previous chunk, and use fig.cap=paste("x is", x)
in the next chunk.
Related Topics
Extract Survival Probabilities in Survfit by Groups
Get Name of X When Defining '(<-' Operator
How to Determine the Geom Type of Each Layer of a Ggplot2 Object
Get Stack Trace on Trycatch'Ed Error in R
Importing Wikipedia Tables in R
R: Save Multiple Plots from a File List into a Single File (Png or PDF or Other Format)
Subset Data Based on Partial Match of Column Names
Dealing with Readlines() Function in R
Using Predict to Find Values of Non-Linear Model
How Would You Fit a Gamma Distribution to a Data in R
R Function Prcomp Fails with Na's Values Even Though Na's Are Allowed
Produce an Inset in Each Facet of an R Ggplot While Preserving Colours of the Original Facet Content
Alternate Geom_Text Position with Hjust
Scraping from Aspx Website Using R
How to Change Color of Facet Borders When Using Facet_Grid
Understanding Dates/Times (Posixc and Posixct) in R
Can .Sd Be Viewed from a Browser Within [.Data.Table()
Why Is the Class of a Vector the Class of the Elements of the Vector and Not Vector Itself