3

I'd like to wrap figures created with knitr and rmarkdown in a "wrapfigure" environment using hooks. However, when running the minimal example below, the figure chunk only gets compiled into a markdown picture:

\begin{wrapfigure}{R}{0.3\textwidth}
![](test_files/figure-latex/unnamed-chunk-2-1.pdf) 
\end{wrapfigure}

and not the expected:

\begin{wrapfigure}{R}{0.3\textwidth}
\includegraphics{test_files/figure-latex/unnamed-chunk-2-1.pdf}
\end{wrapfigure}

Minimal example:

---
header-includes:
   - \usepackage{wrapfig}
output: 
  pdf_document:
    keep_tex: TRUE
---

```{r}
library(knitr)
knit_hooks$set(wrapf = function(before, options, envir) {
  if(before) {
    "\\begin{wrapfigure}{R}{0.3\\textwidth}"
  } else {
    "\\end{wrapfigure}"
  }
})
```

```{r, wrapf=TRUE}
library(ggplot2)
qplot(cars$speed, cars$dist)
```
user2987808
  • 1,387
  • 1
  • 12
  • 28

1 Answers1

2

pandoc is responsible for converting the markdown document to a TEX document. As pandoc doesn't touch between \begin{…} and \end{…} the markdown syntax for the image is not being converted to TEX syntax.

You could …

  • Hide the plot (fig.show = 'hide') and use something along the lines of cat("\includegraphics{figure/unnamed-chunk-2-1.pdf}").
  • Hide the plot as above and include some magic in the hook that saves the cat.
  • Write RNW instead of RMD if you want PDF output.

Here's an example for option 2:

knit_hooks$set(wrapf = function(before, options, envir) {
  if(before) {
    return("\\begin{wrapfigure}{R}{0.3\\textwidth}")
  } else {

    output <- vector(mode = "character", length = options$fig.num + 1)

    for (i in 1:options$fig.num) {
      output[i] <- sprintf("\\includegraphics{%s}", fig_path(number = i))
    }

    output[i+1] <- "\\end{wrapfigure}"
    return(paste(output, collapse = ""))
  }
})

This hook can be used with wrapf = TRUE and fig.show = "hide". (Moreover, you need to add \usepackage{graphics} to header-includes.)

But note that I would not do it! Too many things can go wrong in more complex settings. Think of cache, captions, labels, cache (again!) …

Therefore, if it is really necessary to control the typesetting of the PDF, I recommend writing RNW (option 3).

CL.
  • 14,577
  • 5
  • 46
  • 73