Search code examples
rggplot2gganimate

insert image into ggplot + gganimate when x axis are dates


I want to animate some data using gganimate. Taking an example from their github page I changed it a bit to reflect my case. X-axis are dates and I want a logo in the same position for all frames.

Reproducible code:

library(magick)
library(gapminder)
library(ggplot2)
library(rsvg)
library(gganimate)

tiger <- image_read_svg('http://jeroen.github.io/images/tiger.svg', width = 400)

(p <- ggplot(gapminder, aes(year, lifeExp, size = pop, colour = country)) +
  geom_point(alpha = 0.7, show.legend = FALSE) +
  scale_colour_manual(values = country_colors) +
  scale_size(range = c(2, 12)) +
  scale_x_log10() +
  annotation_raster(tiger, ymin = 75, ymax = 100, xmin = 1965, xmax = 2005) )

# here the animate part (not needed just for ilustrative purposes)

p + labs(title = 'Year: {frame_time}', x = 'Year', y = 'life expectancy') +
  transition_time(year) +
  ease_aes('linear')

The issue is I can plot the logo in any chart when x-axis are not dates.

I suspect this issue is related to date type but no success so far.


Solution

  • Your issue appears to relate to the log scale you are calling for your x-axis. It's taking your year vector — which is not a date, rather a 4-digit integer — and applying a log transformation to it... which as @camille has pointed out means that when you are calling animation_raster the coordinates (xmin / xmax) are off the plot grid.

    Here's a solution that incorporates dates by changing the year in your data frame to a date format. It also layers the image behind the geoms and renders in its original scale ie. 1x1.

    library(magick) 
    library(gapminder)
    library(ggplot2)
    library(rsvg)
    library(gganimate)
    library(lubridate)
    
    tiger <- image_read_svg('http://jeroen.github.io/images/tiger.svg', width = 
    400)
    
    xmin <- ymd("1965/01/01")
    xmax <- ymd("2005/01/01")
    ymin <- 30
    height <- round(as.numeric(xmax-xmin)/356, 0)
    ymax <- ymin + height
    
    gapminder %>%
        mutate(year = ymd(year, truncated = 2L)) %>%
        ggplot() +
        aes(year, lifeExp, size = pop, colour = country) +
        annotation_raster(tiger, ymin = ymin, ymax = ymax, xmin = xmin, xmax = 
        xmax) +
        geom_point(alpha = 0.7, show.legend = FALSE) +
        scale_colour_manual(values = country_colors) +
        scale_size(range = c(2, 12)) +
        labs(title = 'Year: {frame_time}', x = 'Year', y = 'life expectancy') +
        transition_time(year) +
        ease_aes('linear') +
        anim_save("animated_tiger_timeseries.gif")
    

    Which produces this...

    enter image description here

    Is this what you are looking for?