Martin Smith
Martin Smith

Reputation: 4087

Figure name when knitting from R markdown (.Rmd) to Word document (.docx)

I am preparing an .Rmd document that I will render into a .docx. I want the figures to be labelled "Supplementary Figure 1: <Caption>", but I can't see how to override the default addition of "Figure 1: <Caption>" – which is possible for PDF output.

A document template allows me to change the style, but not the text content (as far as I can see).

---
output: 
  bookdown::word_document2: 
    reference_docx: "StyleTemplate.docx"
    fig_caption: true
---

```{r figWithCaption, echo = FALSE, fig.cap = "(ref:caption)"}
variables <- 2
plot(cars) # figure content
` ``

(ref:caption) Caption to the figure might contain _markdown_ $^1$ or `r variables` 

[Edit: Some of my figure captions contain markdown, which is supported by the "bookdown" package but (as far as I can see) not by "officedown"]

Upvotes: 0

Views: 496

Answers (2)

Martin Smith
Martin Smith

Reputation: 4087

The links from @stefan's answer led me to another solution:

Add a file _bookdown.yml to the same directory as MyFile.Rmd, with contents:

language:
  label:
    fig: !expr function(x) sprintf("Supplementary Figure %s. ", x)

Full documentation of this feature is available here.

Upvotes: 0

stefan
stefan

Reputation: 125537

One option to achieve that would be to use the officedown package which enhances the possibilities of RMarkdown for Word considerably, including to set the prefix for figures via the YAML or via chunk options:

---
output: 
  officedown::rdocx_document:
    plots:
      caption:
        pre: "Supplementary Figure "
    fig_caption: true
---

```{r figWithCaption, echo = FALSE, fig.cap = "Caption"}
plot(cars)
```

```{r figWithCaption1, echo = FALSE, fig.cap = "Caption", fig.cap.pre = "Foo "}
plot(cars)
```

enter image description here

EDIT While officedown allows for rendering of markdown I haven't found an option to make your Rmd code work with officedown, i.e. works only if you set the caption in the chunk options.

A second but more advanced approach to achieve your desired result would be to use a LUA filter.

Adapting my answer on this post which is based on this post you could achieve your desired result by creating a LUA filter like so:

function Image (img)
  img.caption[1] = pandoc.Strong(pandoc.Str(string.gsub(img.caption[1].text, "Figure", "Supplementary Figure")))
  return img
end

Which could then be applied in your Rmd like so:

---
output: 
  bookdown::word_document2: 
    fig_caption: true
    pandoc_args: ["--lua-filter", "figure_caption_patch.lua"]
---

```{r figWithCaption, echo = FALSE, , fig.cap = "(ref:caption)"}
variables <- 2
plot(cars)
```

(ref:caption) Caption to the figure might contain _markdown_ $^1$

enter image description here

Upvotes: 1

Related Questions