Search code examples
rggplot2gifanimated-gifgganimate

gganimate creating duplicate legend and caption


I have created an animated plot .gif using gganimate. The problem is that the output has duplicated legend and caption and I don't know what's causing it.

The legend should be in bottom and the caption should be on the bottom left part of the plot. Any ideas on what I'm doing wrong here?

Reproducible example:

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

enter image description here

UPDATE [24-03-2017]: David Robinson, the author of gganimate confirmed to me on Twitter that this strange behavior is caused by a bug that should be fixed sometime soon.

In the mean time, @hrbrmstr's solution looks like a good work around. Another alternative is to use an older version of gganimate, which can be installed like this:

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

Solution

  • Here's a way to do it outside of gganimate.

    Cleaning up the files is an exercise left to the 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")
    

    enter image description here