Search code examples
rlatexknitrr-markdownbeamer

Issue centering plots in Rmarkdown with Beamer class


I have an issue with centering plots in an Rmd document with output type 'beamer presentation.' The same code works fine when the output type is set to 'pdf_document'. When rendering my document I get the error:

! Missing $ inserted.
<inserted text> 
                $
l.74 \end{frame}

pandoc: Error producing PDF
Error: pandoc document conversion failed with error 43

The strange thing is that I get this error both when knitting using the command render("slideshow.Rmd",output_file = "Demo slideshow.pdf"), as well as when pressing 'Knit' in the Rstudio GUI, but in the latter I am presented with a pdf in which the plot is centered anyway.

Edit: in hindsight, this may not have been true. When rendering through the console statement, output is printd in the 'console' tab of the console. When rendering through the 'Knit'-button, output is printed to the 'R markdown' tab of the console, and after it finishes it goes back to the 'console' tab automatically, where the error of the previous render statement is still displayed. enter image description here

I have tried

```{r, results = 'asis', echo = FALSE, fig.width=5, warning=FALSE, message=FALSE}

in which case the error does not appear, but the plot is left-aligned. Wrapping this code chunk in \begin{center} and \end{center} leaves me with the same error again.

Any help is appreciated, thanks in advance for any suggestions.


slideshow.Rmd

---
title: Oh man
subtitle: this issue is
author: really bugging me
fontsize: 10pt
output: beamer_presentation

---

```{r setup, include=FALSE, warning=FALSE, message=FALSE}
knitr::opts_chunk$set(echo = T)

df=data.frame(x=c(1,2,3),y=c(1,2,3))

```


### This is a title
And this is some text 

```{r, results = 'asis', echo = FALSE, out.width='80%', warning=FALSE, message=FALSE, fig.align='center'}

plot(df$x,df$y)

```

Solution

  • For future reference, if anyone else might stumble into this problem, I think I solved it. I set 'keep_tex=TRUE like this:

    output:
      beamer_presentation:
        keep_tex: true
    

    I investigated the tex file around line 74 (since that line is mentioned in the error l.74 \end{frame} Two lines before that, was:

    \begin{center}\includegraphics[width=0.8\linewidth]
      {--path--/Demo slideshow_files/figure-beamer/unnamed-chunk-1-1} \end{center}
    

    where --path-- is abbreviated here. As I specified in the resulting filename, there is a space between Demo and slideshow. This seems to have caused the error.

    render("slideshow.Rmd",output_file = "Demo_slideshow.pdf")
    

    works fine.