Export plots in WebP format

Since there’s no “built in” way to export R graphs to WebP images, {webpea} offers a function to save single plots or to automate WebP export in quarto / Rmd documents.


February 25, 2023


Common forms to save plots in R include PNG or SVG. Both have their advantages, be it e.g. versatility or scalability. I learned about the WebP image file format recently and that it is supported by all major web browsers1. The format offers considerable compression improvements over PNG with no apparent visual accuracy loss (in default settings).

There are, of course, command line tools to convert image files for UNIX systems. There’s ImageMagick for Linux and apparently SIPS for MacOS2. However this is not a practical approach for when you want to write an Rmd report or e.g. Quarto blog post, just like this one.

In comes {webpea}, an experimantal R package to ease this process. It’s just a small package and at this stage a simple wrapper function, that combines ggplot2’s ggsave() with the magick package. For the basic implementation, please refer to the manual or the README.

The Old Way

First let’s draw a plot, the default way.

#| fig-width: 8
#| fig-height: 6


ggplot(diamonds) +
  aes(price, carat, color = as.factor(cut)) +
  geom_point(alpha = 0.5, size = 3) +

In “default quarto rendering” the above plot will be included as PNG with a resolution of 1536 x 1152 px and a size of 641,73 KB.

Automate WebP Export and Inclusion in the HTML output

Since we want to have a WebP version, let’s store the plot in a variable, thus it won’t get printed to the output. webpea::webpea() returns the file path/name. We can use this to put the function directly into the “src=” argument of htmltools::img().

p <- ggplot(diamonds) +
  aes(price, carat, color = as.factor(cut)) +
  geom_point(alpha = 0.5, size = 3) +

  src = webpea(
    plot = p, 
    height = 6, 
    width = 8, 
    path_return = FALSE
  width = "100%"

The second plot is a WebP image with a resolution of 2400 x 1800 px and a file size of 154,31 KB. Even if the image has a slightly higher resolution, the file size is a quarter of the original PNG.


WebP offers a great improvement in file compression without relevant quality loss. In fact, if you open both image files above with 100% zoom: can you spot significant differences? I can’t, but I’d still be interested in your feedback. So let me know in the comments below.


  1. https://caniuse.com/webp↩︎

  2. Thanks to @hrbrmstr for the pointer↩︎



BibTeX citation:
  author = {Gebhard, Christian},
  title = {Export Plots in {WebP} Format},
  date = {2023-02-25},
  url = {https://christiangebhard.com/posts/2023-02-25-webpea-sample/2023-02-25-webpea-sample.html},
  langid = {en}
For attribution, please cite this work as:
Gebhard, Christian. 2023. “Export Plots in WebP Format.” February 25, 2023. https://christiangebhard.com/posts/2023-02-25-webpea-sample/2023-02-25-webpea-sample.html.