Auto-Numbering of Figure and Table Captions for HTML Output in R Markdown - r-markdown

Is there a way to automatically number the figures in captions when I knit R Markdown document into an HTML format?
What I would like is for my output to be the following:
Figure 1: Here is my caption for this amazing graph.
However, I am currently getting the following:
Here is my caption for this amazing graph.
Here is my MWE:
---
title: "My title"
author: "Me"
output:
html_document:
number_sections: TRUE
fig_caption: TRUE
---
```{r setup}
knitr::opts_chunk$set(echo=FALSE)
```
```{r plot1,fig.cap="Here is my caption for this amazing graph."}
x <- 1:10
y <- rnorm(10)
plot(x,y)
```
```{r table1, fig.cap="Here is my caption for an amazing table."}
head(mtcars, 2)
```
I have read that this issue is resolved with Bookdown but I've read the Definitive Guide to Bookdown, cover to cover, and can't find it.

If you wish to have numbered figures, you will need to use an output format provided by bookdown. These include html_document2, pdf_document2 etc. See here for a more comprehensive list of options.
Changing your document example html_document to bookdown::html_document2 will resolve your problem.
---
title: "My title"
author: "Me"
output:
bookdown::html_document2:
number_sections: TRUE
fig_caption: TRUE
---
```{r setup}
knitr::opts_chunk$set(echo=FALSE)
```
```{r plot1,fig.cap="Here is my caption for this amazing graph."}
x <- 1:10
y <- rnorm(10)
plot(x,y)
```
```{r plot2, fig.cap="Here is my caption for another amazing graph."}
plot(y,x)
```
If you want to label tables created by knitr::kable, you will need to specify the caption within the table call itself
```{r table1}
knitr::kable(mtcars[1:5, 1:5], caption = "Here is an amazing table")
```

Related

Greek letters RMarkdown PDF plots

I'm trying to generate Greek letters in the axis labels or titles of plots in an RMarkdown file that is generating a PDF. When I run the code the editor or in the console, I see the letter fine, but when the PDF is generated, they disappear. In the short example below, I can see that the subscript operation is working but the Greek letter theta isn't present.
I've tried changing the Typeset LaTeX in PDF using: option - I have pdfLaTeX and XeLaTex - but I see no difference.
---
title: "Untitled"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
plot(1:100, 1:100, xlab = expression(theta[5]))
plot(1:100, 1:100, xlab = expression('theta'[5]))
```
I was using Latin modern font and came across the same problem. The following code fixed it for me. Make sure the math library for the font you are using is called for.
---
title: "Untitled"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, fig.showtext=TRUE}
library("showtext")
font_add("LM Roman 10", regular = "/usr/share/texmf/fonts/opentype/public/lm/lmroman10-regular.otf")
font_add("LM Roman 10", regular = "/usr/share/texmf/fonts/opentype/public/lm-math/latinmodern-math.otf")
plot(1:100, 1:100, xlab = expression(theta[5]))
```

Adding a letter to all table numbers in RMarkdown

I'm using RMarkdown to create Supplementary documents for a paper. These supplements contain many tables. Let's call these documents Supplement A and Supplement B. I want the table numbering to reflect the supplement letter, that is, Table A1 or Table 1A for the first table in Supplement A and so on for all tables.
How can I modify the table numbering to add a letter into the table numbering schema?
Here's an example that will produce a table with normal numbering:
---
title: "Supplement A"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
```
```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption="MTCars") %>%
kable_styling(latex_options="hold_position", position="left")
```
An inelegant solution using the captioner package (details provided here: https://datascienceplus.com/r-markdown-how-to-number-and-reference-tables/) can create captions and insert them manually just before the code chunk. Combining this with the Latex package caption makes it possible to remove the automatic table naming and numbering if the caption is generated within the code chunk (How to suppress automatic table name and number in an .Rmd file using xtable or knitr::kable?). I've done this in the YAML with \captionsetup[table]{labelformat=empty}, but it can be done in the document body also. Either way, the caption can then be generated within the code chunk, which was important in my case.
This solution stops bookdown referencing from working (because labelformat cannot be empty), but a workaround for table referencing was provided in the link for using the captioner package (and is included below).
---
title: "Supplement A"
header-includes:
- \usepackage{caption}
\captionsetup[table]{labelformat=empty}
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(captioner)
library(stringr)
```
```{r captions}
# Create the caption(s)
caption <- captioner("Table A", FALSE)
tab_1_cap <- caption("Tab_1", "MTCars")
# Create a function for referring to the tables in text
ref <- function(x) str_extract(x, "[^:]*")
```
The following table is `r ref(tab_1_cap)`.
```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption=tab_1_cap) %>%
kable_styling(latex_options="hold_position", position="left")
```
An alternative solution is avaiable via LaTeX. Add the following somewhere in the body of the document to change the default figure and table names to include the letter.
\def\figurename{Figure A}
\def\tablename{Table A}
To reference a table or figure in text use, e.g., Table A\#ref(tab:label), after defining the table label as normal.
This alone will leave a space in the table/figure caption (e.g., 'Table A 1' instead of 'Table A1'). This can be solved by adding the following to the YAML:
header-includes:
- \usepackage{caption}
- \DeclareCaptionLabelFormat{nospace}{#1#2}
- \captionsetup[figure]{labelformat=nospace}
- \captionsetup[table]{labelformat=nospace}
The \DeclareCaptionLabelFormat creates a function (here labeled nospace), which overrides the default caption label when called. #1 represents the label assigned to refer to tables or figures (e.g., 'Table A') and #2 represents the number of the table or figure. The captionsetup lines change the label format for all tables and figures to the format defined by 'nospace'.
Thus, the code produces, e.g., 'Table A1: Table name' as the caption. If instead you wanted, e.g., 'Table A-1: Table name', the code in \DeclareCaptionLabelFormat should be changed to {#1-#2}.
---
title: "Supplement A"
output: bookdown::pdf_document2
toc: false
header-includes:
- \usepackage{caption}
- \DeclareCaptionLabelFormat{nospace}{#1#2}
- \captionsetup[figure]{labelformat=nospace}
- \captionsetup[table]{labelformat=nospace}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(bookdown)
```
\def\figurename{Figure A}
\def\tablename{Table A}
See Table A\#ref(tab:cars) for something about cars.
(ref:cars) Table caption
```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption="(ref:cars)") %>%
kable_styling(latex_options="hold_position", position="left")
```
Answer inspired by: Figure name in caption using RMarkdown
Caption latex package documentation: https://ctan.org/pkg/caption

How to embed highcharter in rmarkdown to share (not a loop)

I cannot get two simple highcharter charts in an Rmarkdown file I want to share. It works fine and renders in my PC or Mac, but when I share the file, people only see text.
They are not part of a loop, as mentioned in few articles. They are just two charts. For the reproducible example, I literally just opened a new rmarkdown doc and selected html. I replaced the "summary table" of cars with highcharter code. I even tried htmltools::tagList(chart1, chart2) and it does not work.
I am supplying the code. If you please show me how to do it with one chart, I can do it with the second.
Thank you.
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```{r echo=FALSE}
library(magrittr)
library(highcharter)
highchart() %>%
hc_add_series(cars, type = "scatter", hcaes(speed, dist))
I apologize if the tick marks hide the code background, but the three chunks are wrapped with the three tickmarks at the beginning and end of each chunk.
Thank you again.
Yes the code below produces the file below the code. I now have an entire .html file that has the highchart self contained in the file.
---
output:
html_document:
self_contained: yes
mode: selfcontained
---
{r echo=FALSE}
library(magrittr)
library(highcharter)
highchart() %>%
hc_add_series(cars, type = "scatter", hcaes(speed, dist))

Restart Figure Numbering for Appendix / Supplementary Material in bookdown

I am writing an article for a journal that requires Supplementary Material. I was hoping to use a unique label such as SuppMat: instead of the default fig: to send Figures and Tables into this section. If not, I can use the default fig label but I need numbering to restart in the Supplementary Material section of the document.
I am aware of one answer using latex (found here) but I must complete this when exporting to docx. Below is a reproducible example using officedown
---
output:
officedown::rdocx_document
---
```{r setup, include=FALSE}
pacman::p_load(knitr, officedown, officer)
knitr::opts_chunk$set(echo = FALSE,
eval = TRUE,
fig.cap = TRUE)
```
# Main Text
Please see Supplementary Figure \#ref(fig:appendix-fig1) and Figure \#ref(fig:main-fig1).
```{r fig.id="main-fig1", fig.cap="This should be labelled **Figure 1**"}
barplot(1:5, col=1:5)
```
```{r tab.id="main-tab1", tab.cap="Main Text Table 1"}
head(mtcars)
```
\newpage
# Supplementary Materials {#SuppMat}
```{r fig.id="appendix-fig1", fig.cap="This figure should be labelled **Supplementary Figure 1**"}
barplot(1:5, col=1:5)
```
```{r tab.id="appendix-tab1", tab.cap="Should be labelled **Supplementary Table 1**"}
head(mtcars)
```
After searching multiple forums and hours, I was able to come up with a solution using the officedown package. Hopefully this helps someone else out. For further details check out the run_autonum function.
---
output: officedown::rdocx_document
---
```{r setup, include=FALSE}
pacman::p_load(officedown, officer, knitr)
knitr::opts_chunk$set(echo = FALSE, fig.cap = TRUE)
ft_base <- fp_text(font.family = "Cambria", font.size = 12, bold = TRUE)
ft1 <- update(ft_base, shading.color='#EFEFEF', color = "red")
ft2 <- update(ft_base, color = "#C32900")
srcfile <- file.path( R.home("doc"), "html", "logo.jpg" )
extimg <- external_img(src = srcfile, height = 1.06/5, width = 1.39/5)
```
## References
This is a reference to an supplementary image caption whose number is Supplementary Figure \#ref(fig:faithfuld-plot) and \#ref(fig:supp-bar).
Testing another figure with a barplot in Figure \#ref(fig:plotbar)
```{r fig.id="plotbar", fig.cap = "Main Figure"}
barplot(1:8, col=1:2)
```
## Supplementary Material
```{r fig.id="faithfuld-plot"}
knitr::include_graphics("images/MyImage.png") # Use your own figure here (I needed to test with knitr for my workflow)
block_caption("First Appendix Figure",
style = "Figure",
autonum = run_autonum(seq_id = 'fig',
bkm = 'faithfuld-plot',
pre_label = "Supplemental Figure ",
start_at=1))
```
```{r fig.id="supp-bar"}
barplot(1:8, col=1:2)
block_caption("Second Appendix Figure",
style = "Figure",
autonum = run_autonum(seq_id = 'fig',
bkm = 'supp-bar',
pre_label = "Supplemental Figure ",
start_at= NULL))
```

How to rotate or adjust a big table in Rmarkdown?

Here is my example:
---
title: "There is a reproductible example"
output: pdf_document
---
```{r table-simple, echo=FALSE, message=FALSE, warnings=FALSE, results='asis'}
require(pander)
panderOptions('table.split.table', Inf)
set.caption("My great data")
my.data <- " # replace the text below with your table data
Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement
Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement
Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement
Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement "
df <- read.delim(textConnection(my.data),header=FALSE,sep="|",strip.white=TRUE,stringsAsFactors=FALSE)
names(df) <- unname(as.list(df[1,])) # put headers on
df <- df[-1,] # remove first row
row.names(df)<-NULL
pander(df, style = 'rmarkdown')
```
In the final PDF outputs, Words overlap.
I use "kable", "table", "print"
Do you have an idea that the words do not overlap?
If the table is very huge, I want that the table rotate automatically in landscape format. Is it possible?
You could try to add the option:
classoption: landscape
in your head section
---
title: "There is a reproductible example"
output: pdf_document
classoption: landscape
---
This will produce a landscape version of the document.