jakob r jakob r - 3 months ago 8
R Question

R: Plot multiple file formats at once

Originally I wanted to knit a document and generate svg and png versions of the plots at the same time.

I checked the documentation of knitr and found out that in

opts_chunk$set(dev = ...)
you can set your own function which accepts plots.

But this is also not so easy as the call of
svg(); pdf()
opens both devices but just the last one will generate the output.

Any ideas?

Answer

If you are working with RMarkdown, and attempting to have each plot outputted in multiple formats, you can do:

---
output:
  html_document:
    self_contained: false
---

```{r}
library(knitr)
opts_chunk$set(dev=c('png', 'svg'))
```

```{r}
plot(rnorm(10), rnorm(10))
```

If your file is named "README.Rmd", then the images will be saved to README_files/figure-html/.

The self_contained yaml parameter tells rmarkdown to save images (and other resources such as JavaScript) externally, instead of embedding them directly in the HTML file.

The dev option (see knitr docs) can simply be passed a vector of all the formats you wish to save the plot as.

Comments