Search code examples
rplotr-markdownfigure

Issues plotting multiple plots in a single figure within RMarkdown


I have plot function that produce four plots like glm. A histogramm, a boxplot and two scatterplots. But I cant put them in the right place in my document so that I can see all informations. I want 2 plots in 1 row and to be wide so I can see all informations like header etc.

It's senseless to post my plot function, because it's for a class that I created.

My output looks always like this enter image description here

I have the following YAML layout:

---
title: 
author:
fontsize: 11
graphics: true
documentclass: article
output: 
  pdf_document:
    fig_caption: yes
    toc: true
    latex_engine: pdflatex
    toc_depth: 2
    number_sections: true
    keep_tex: true
header-includes: 
- \usepackage{graphicx}
- \usepackage{float}
- \usepackage{subfig}
---

```{r setup, include = FALSE}
library(knitr)
knitr::opts_chunk$set(fig.path = 'figures/', fig.pos = 'htb!', echo = TRUE)
knit_hooks$set(plot = function(x, options)  {
  hook_plot_tex(x, options)
})
```

```{r, out.width='1\\linewidth', fig.asp=0.5, fig.ncol = 1, fig.cap="output",fig.align = "center"}
par(mfrow = c(1, 2))
plot(poisReg)
```

Solution

  • I am failing to replicate your problem. Using a reproducible set of plots:

    ---
    title: 
    author:
    fontsize: 11
    graphics: true
    documentclass: article
    output: 
      pdf_document:
        fig_caption: yes
        toc: true
        latex_engine: pdflatex
        toc_depth: 2
        number_sections: true
        keep_tex: true
    header-includes: 
    - \usepackage{graphicx}
    - \usepackage{float}
    - \usepackage{subfig}
    ---
    
    ```{r setup, include = FALSE}
    library(knitr)
    knitr::opts_chunk$set(fig.path = 'figures/', fig.pos = 'htb!', echo = TRUE)
    knit_hooks$set(plot = function(x, options)  {
      hook_plot_tex(x, options)
    })
    ```
    
    ```{r, out.width='1\\linewidth', fig.asp=0.5, fig.ncol = 1, fig.cap="output",fig.align = "center"}
    par(mfrow = c(1, 2))
    plot(cars, main = "Title 1")
    plot(cars, main = "Title 2")
    plot(cars, main = "Title 3")
    plot(cars, main = "Title 4")
    ```
    

    enter image description here

    It seems to me that something is being messed up the knitr setting up the figures folder.