Search code examples
rr-markdownpdf-generationknitrxaringan

R Markdown missing plots when I print to PDF from xaringan


This stackoverflow solution describes a method (through the xaringanBuilder package) to build your xaringan slides to various formats (html, pdf, pptx, etc). Unfortunately, it doesn't solve the issue I'm having:

---
title: "Presentation Ninja"
output:
  xaringan::moon_reader:
    lib_dir: libs
    nature:
      highlightStyle: github
      highlightLines: true
      countIncrementalSlides: false
---

# xaringan plot that won't print to pdf

```{r cars, fig.height=4, dev='svg'}
par(mfrow = c(2, 2))
plot(mtcars$mpg, mtcars$cyl)
plot(mtcars$disp, mtcars$hp)
plot(mtcars$drat, mtcars$wt)
plot(mtcars$qsec, mtcars$vs)
```

When I knit the xaringan R Markdown code above it works as expected:

  1. A plot is generated consisting of four figures.
  2. I can view the HTML in my browsers (Edge, Chrome)

I then proceed to print to PDF from Edge (or Chrome), the PDF is generated, and the plots are missing from the output. I've made sure to enable include background graphics when printing to pdf. Why do the plots go missing, and how do I keep the plots in the PDF output?

Building with xaringanBuilder doesn't solve the issue either, the plot is still missing from the output.


Solution

  • A little intro:

    As I came to the conclusion in the previous answer in order to "activate" print function in xaringan presentation - one needs to add @media print css rule.

    Returning to your question and adding @media print rule - we can see the next results.

    Code:

    ---
    title: "Presentation"
    output:
      xaringan::moon_reader: default
    ---
    
    <style>
    @media print{
      body, html, .remark-slides-area, .remark-notes-area {
        height: 100% !important;
        width: 100% !important;
        overflow: visible;
        display: inline-block;
        }
    </style>
    
    # xaringan plot which prints to pdf
    
    ```{r cars, fig.height=4, dev='svg', echo = F}
    par(mfrow = c(2, 2))
    plot(mtcars$mpg, mtcars$cyl)
    plot(mtcars$disp, mtcars$hp)
    plot(mtcars$drat, mtcars$wt)
    plot(mtcars$qsec, mtcars$vs)
    ```
    

    Output:

    enter image description here