【问题标题】:Suppress alt text for GIFs in rmarkdown HTML output在 rmarkdown HTML 输出中抑制 GIF 的替代文本
【发布时间】:2017-10-03 06:30:12
【问题描述】:

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

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

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

【问题讨论】:

  • 在您的animation.fun 中使用{r, label = 'mylabel'} 或使用sprintf("![%s](%s)", options$fig.cap, paste0(opts_knit$get("base.url"), mov.fname))(然后使用fig.cap)是否满足您?
  • 另外,我认为模拟hook_plot_html 的默认输出是一个更好的选择:sprintf('&lt;div class="figure %s"&gt;&lt;img src="%s"&gt;&lt;p class="caption"&gt;%s&lt;/p&gt;&lt;/div&gt;', options$fig.align, mov.fname, options$fig.cap)
  • @martin 是的,模拟hook_plot_html 的输出正是我想要的!我你提交,我回答我可以接受。
  • 很高兴它成功了。

标签: r knitr r-markdown gganimate


【解决方案1】:

这里的问题是您将生成的动画包含在降价语法中。我猜这会引入一些问题。

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

【讨论】:

    猜你喜欢
    • 2017-08-08
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    相关资源
    最近更新 更多