在rmarkdown HTML输出中禁止GIF的替代文字

时间:2017-05-04 22:22:18

标签: r knitr r-markdown gganimate

我正在使用RMarkdown文件中的 gganimate 包生成GIF。在前端使用output = github_document时,GIF会在输出(github-document-output)中按预期显示。但是,使用output = html_document时,GIF会生成alt文本,默认为块名称(html-document-output)。

有没有办法抑制这个自动标题?我尝试使用fig.cap chunk选项设置我自己的标题,但这不成功。

RMarkdown代码

---
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)
```

1 个答案:

答案 0 :(得分:1)

这里的问题是您使用markdown语法包含结果动画。这引入了一些我认为的精神。

看一下hook_plot_html,我们可以模拟标准图的默认输出:

sprintf(paste0('<div class="figure %s">',
               '<img src="%s">',
               '<p class="caption">%s</p>',
               '</div>'), options$fig.align, mov.fname, options$fig.cap)