Search code examples
rgganimate

How to set geom_density_2d_filled as background in gganimate


I try to use geom_density_2d_filled as background in my animation:

library(tidyverse)
library(gganimate)

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

but I have no background in this case.

When I use geom_density_2d instead of geom_density_2d_filled everything is ok. What am I doing wrong?


Solution

  • I think transition_reveal is looking for an mpg variable for each layer.

    If you add

    mtcars_$mpg = min(mtcars$mpg)
    

    it will plot with the background, but MUCH slower because that layer takes more computing per frame than the line. If that's a problem you might look at an alternative, like saving the background to an image and printing the image as a bottom layer.