Search code examples
rgganimate

How to set alpha parameter for background in gganimate


I try to set alpha parameter 0.1 for background in my animation:

library(tidyverse)
library(gganimate)

mtcars_ <- rename(mtcars, mpg_ = mpg, disp_ = disp)
mtcars_$mpg = min(mtcars$mpg)
gg <- ggplot(mtcars, aes(x = mpg, y = disp)) + geom_density_2d_filled(data = mtcars_, aes(x = mpg_, y = disp_), alpha = 0.1) + geom_line() + theme(legend.position = "none")
gg
anim <- gg + transition_reveal(mpg) + shadow_wake(1)
anim

but alpha is 1 in final movie. How to fix it?

I need movie with this image enter image description here


Solution

  • One way to do this would be to replicate the data you need for each frame. geom_density should see everything in every frame, but geom_line should only "see" the values up to the currently displayed value. We could accomplish that using tidyr::uncount to make copies of our data, and then creating a variable for geom_line that is NA when the value is too high for the current frame.

    library(tidyverse)
    library(gganimate)
    
    distinct_mpg <- mtcars %>% distinct(mpg) %>% arrange(mpg) %>% pull(mpg)
      
    mtcars_frames <- mtcars %>%
      uncount(length(distinct_mpg), .id = "frame") %>%
      mutate(mpg_reveal = distinct_mpg[frame],
             mpg_shown = if_else(mpg <= mpg_reveal, mpg, NA_real_)) 
    
    animate(
      ggplot(mtcars_frames, aes(y = disp)) +
        geom_density_2d_filled(aes(x = mpg), alpha = 0.1) + 
        geom_line(aes(x = mpg_shown, group = frame)) +
        transition_states(frame) +
        scale_fill_viridis_d(guide = NULL),
      fps = 20
    )
    

    enter image description here