如何在 gganimate 中将 geom_density_2d_filled 设置为背景

How to set geom_density_2d_filled as background in gganimate

我尝试在我的动画中使用 geom_density_2d_filled 作为背景:

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

但我没有这方面的背景。

当我使用 geom_density_2d 而不是 geom_density_2d_filled 时,一切正常。我做错了什么?

我认为 transition_reveal 正在为每一层寻找一个 mpg 变量。

如果你添加

mtcars_$mpg = min(mtcars$mpg)

它将与背景一起绘制,但速度要慢得多,因为该层每帧比线条需要更多的计算。如果这是一个问题,您可能会考虑替代方案,例如将背景保存到图像并将图像打印为底层。