gganimate 创建重复的图例和标题

gganimate creating duplicate legend and caption

我使用 gganimate 创建了动画情节。gif。问题是输出有重复的图例和标题,我不知道是什么原因造成的。

图例应在底部,标题应在图的左下角。关于我在这里做错了什么有什么想法吗?

可重现的例子:

library(gapminder)
library(ggplot2)
library(gganimate)
library(viridis)

t <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent, frame = year)) +
        geom_point() +
        scale_color_viridis(name="Continent", discrete=TRUE) +
        scale_x_log10() +
        theme_void() + 
        theme( legend.position = "bottom", legend.box = "vertical", legend.title.align = 0) +
        labs(title = "Year: ") +
        labs(caption = " Caption test") +
        theme(plot.title = element_text(hjust = 0.5, vjust = 0.05)) +
        theme(plot.caption = element_text(hjust = 0, color="gray40", size=10)) 



gganimate(t, "output_test.gif")

更新 [24-03-2017]:gganimate 的作者大卫·罗宾逊在 Twitter 上向我确认,这种奇怪的行为是由一个应该很快修复的错误引起的。

与此同时,@hrbrmstr 的解决方案看起来是一个不错的解决方案。另一种选择是使用旧版本的 gganimate,可以这样安装:

  library(devtools)
  install_github("dgrtwo/gganimate", ref = "26ec501")

gganimate_save 有一些问题。在文档的详细信息下,它指出:

If saving to a GIF, uses a custom method that takes advantage of redundant backgrounds (scales, static layers, etc).

除了显示两组轴的 gif 之外,第一个图像除了水平轴外都是空白的。

如果您改为调用

gganimate(t, "output_test.mp4")

然后生成的电影如预期。

然后您可以在 mp4 上调用 imagemagick 以转换为 gif,在 bash(或适应来自 R 的系统调用):

> convert output_test.mp4 output_test.gif

来自 R:

system('convert output_test.mp4 output_test.gif')

这是一种在 gganimate 之外进行的方法。

清理文件是留给 reader 的练习:-)

library(gapminder)
library(viridis)
library(magick)
library(tidyverse)

td <- tempdir()

years <- sort(unique(gapminder$year)) 

pb <- progress_estimated(length(years))

map_chr(years, ~{

  pb$tick()$print()

  filter(gapminder, year == .x) %>% 
    ggplot(aes(gdpPercap, lifeExp, size = pop, color = continent)) +
    geom_point() +
    scale_color_viridis(name="Continent", discrete=TRUE) +
    scale_x_log10() +
    labs(title = sprintf("Year: %s", .x)) +
    labs(caption = " Caption test") +
    guides(colour = guide_legend(order = 2), shape = guide_legend(order = 1)) +
    theme_void() + 
    theme(legend.position = "bottom", legend.box = "vertical", legend.title.align = 0) +
    theme(plot.title = element_text(hjust = 0.5, vjust = 0.05)) +
    theme(plot.caption = element_text(hjust = 0, color="gray40", size=10)) -> gg 

  fil <- file.path(td, sprintf("%04d.png", as.integer(.x)))

  ggsave(fil, width=5, height=3, gg)

  fil

}) %>% 
  map(image_read) %>% 
  image_join() %>% 
  image_animate(fps=2, loop=1) %>% 
  image_write("animated.gif")