rr-markdownfigures

Numbering figures of plot(glm) in rmarkdown


I created a Rmarkdown document and want to number my figures. What I am struggling with is if a plot gives me several output like plot("glm Object")?

Here is a minimal example:

---
documentclass: article
output: pdf_document
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(fig.path = 'figures/', fig.pos = 'htb!', echo = TRUE)
```

```{r, fig.cap = "Test"}
data(warpbreaks)
daten <- as.data.frame(warpbreaks)
test <- glm(breaks ~ tension + wool , family = "poisson", data = daten)
plot(test)
```

Solution

  • You can use a lesser-known feature of Rmarkdown and add captions to subfigures: https://stackoverflow.com/a/49086985/7347699

    For your example:

    ---
    documentclass: article
    output: pdf_document
    header-includes:
       - \usepackage{subfig}
    ---
    
    ```{r setup, include = FALSE}
    knitr::opts_chunk$set(fig.path = 'figures/', fig.pos = 'htb!', echo = TRUE)
    ```
    
    ```{r, fig.cap = "Test",  fig.subcap=c('sub 1', 'sub 2', 'sub 3', 'sub 4'), out.width='.49\\linewidth', fig.asp=1, fig.ncol = 2}
    data(warpbreaks)
    daten <- as.data.frame(warpbreaks)
    test <- glm(breaks ~ tension + wool , family = "poisson", data = daten)
    plot(test)
    ```
    

    enter image description here

    Alternative Approach

    A potentially easier way plotting multiple R plots is to use the par function before plotting. The benefit of this is its simplicity, and that you do not need to load addition LaTeX packages in the header. However, it is not possible to add a sub-caption to each plot.

    ---
    documentclass: article
    output: pdf_document
    ---
    
    ```{r, fig.cap = "Test", fig.asp = 1}
    data(warpbreaks)
    daten <- as.data.frame(warpbreaks)
    test <- glm(breaks ~ tension + wool , family = "poisson", data = daten)
    
    par(mfrow = c(2, 2))
    plot(test)
    ```
    

    enter image description here