Keeping Figures in an Rmd – Word Document

random-code-snippets reproducibility rmarkdown

How to make your rmarkdown to word conversion also generate a directory of figures.

Robert M Flight true

I’ve been working with a lot of collaborators who expect Word documents lately. I don’t really like it, but it makes it a lot easier for them to edit and work with things back and forth. So I’ve really been working on generating nice output in the Word document.

Recently, someone brought up collecting the figures for a manuscript for submission. For those in the know, when you submit a manuscript, you often submit the text with or without figures embedded, and then you also submit “high” resolution figure files separately (yes it’s annoying, but that’s the way it is for many submission systems). Now, you could plot twice in each chunk, but thats freaking annoying. Ideally, Rmarkdown or knitr should do all the work for us. And thanks to the R Markdown Cookbook (Xie 2021), there is a simple way to do this.

In the yaml preamble, simply set the parameter: keep_md: true, like this:

    keep_md: true

This means the markdown intermediate is kept, as well as the directory of figures. The figures will be named with the name of the chunk, so you will want to name your chunks well to make it easy to find the figures.

You can also control where your figures get written to, as well as the default figure size, output type, and resolution.

This chunk sets the directory (path) the dpi to 300, to use cairo PNG output, the figure width to 8 in, height to 5 in. And then creates the directory (which I’m sure knitr does, but this is for my own sanity).

# the trailing slash is important!
fig_dir = here::here("doc", "figure_directory/") 
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, dpi = 300,
                      dev.args = list(png = list(type = "cairo")),
                      fig.width = 8, fig.height = 5,
                      fig.path = fig_dir)
if (!dir.exists(fig_dir)) {

Edit: I rolled all of this functionality into a little package documentNumbering.

Xie, C; Riederer, Y; Dervieux. 2021. “R Markdown Cookbook.”



If you see mistakes or want to suggest changes, please create an issue on the source repository.


Text and figures are licensed under Creative Commons Attribution CC BY 4.0. Source code is available at, unless otherwise noted. The figures that have been reused from other sources don't fall under this license and can be recognized by a note in their caption: "Figure from ...".


For attribution, please cite this work as

Flight (2021, July 22). Deciphering Life: One Bit at a Time: Keeping Figures in an Rmd -- Word Document. Retrieved from

BibTeX citation

  author = {Flight, Robert M},
  title = {Deciphering Life: One Bit at a Time: Keeping Figures in an Rmd -- Word Document},
  url = {},
  year = {2021}