0

I'm generating GIFs using the gganimate package within an RMarkdown file. When using output = github_document in the front matter, the GIF appears as expected in the output (github-document-output). However, when using output = html_document, the GIF generates with alt text, which defaults to the chunk name (html-document-output).

Is there a way to suppress this automatic caption? I've tried setting my own caption using the fig.cap chunk option, but that was unsuccessful.

RMarkdown code

---
output:
  html_document: default
  github_document: default
---

```{r}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "output/test-fig-",
  cache.path = "output/test-cache-"
)
```


```{r cache = FALSE}
library(knitr)
library(animation)
ani.options(autobrowse = FALSE, interval = 1)

opts_knit$set(animation.fun = function(x, options, format = "gif") {
  x = c(knitr:::sans_ext(x), knitr:::file_ext(x))
  fig.num = options$fig.num
  format = sub("^[.]", "", format)
  fig.fname = paste0(sub(paste0(fig.num, "$"), "*", x[1]), 
                     ".", x[2])
  mov.fname = paste0(sub(paste0(fig.num, "$"), "", x[1]), ".", 
                     format)

  # order correctly
  figs <- Sys.glob(fig.fname)
  figs <- figs[order(as.numeric(stringr::str_match(figs, paste0("(\\d+)\\.", x[2]))[, 2]))]

  animation::im.convert(figs, output = mov.fname)

  sprintf("![%s](%s)", options$label, paste0(opts_knit$get("base.url"), mov.fname))
})

opts_chunk$set(cache = TRUE, message = FALSE, warning = FALSE, fig.show = "animate")
```

```{r pkgs, cache = FALSE}
library(gapminder)
library(ggplot2)
theme_set(theme_bw())
```

```{r setup}
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent, frame = year)) +
  geom_point() +
  scale_x_log10()
```

```{r dependson = "setup"}
library(gganimate)

gg_animate(p)
```
Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
Jake Thompson
  • 2,591
  • 1
  • 16
  • 32

1 Answers1

1

The problem here is that you include the resulting animation with markdown syntax. This introduces some iiritations I guess.

Taking a look at hook_plot_html we can simulate the default output for standard plots:

sprintf(paste0('<div class="figure %s">',
               '<img src="%s">',
               '<p class="caption">%s</p>',
               '</div>'), options$fig.align, mov.fname, options$fig.cap)
Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98