如何在 gganimate 中为背景设置 alpha 参数

How to set alpha parameter for background in gganimate

我尝试在我的动画中为背景设置 alpha 参数 0.1:

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

但在最终电影中 alpha 为 1。如何解决?

我需要有这张图片的电影

您可能只想删除 shadow_wake() 或将其 wake_length 设置为更接近 0。视觉结果将相似,但 [=28= 的计算时间会更长]() 选项。

gg1 <- ggplot(mtcars, aes(x = mpg, y = disp)) + 
  geom_density_2d_filled(data = mtcars_, aes(x = mpg_, y = disp_), alpha = 0.2) + geom_line() + 
  theme(legend.position = "none",
        panel.background = element_blank())

gg1 + transition_reveal(mpg)

shadow_wake() 删除

或将 shadow_wake 设置为较低的设置。

gg2 <- 
  ggplot(data = mtcars, aes(x = mpg, y = disp)) + 
  geom_density_2d_filled(data = mtcars_ , aes(x = mpg_, y = disp_), alpha = 0.2) + 
  geom_line() + 
  theme(legend.position = "none",
        panel.background = element_blank())

 gg2 + transition_reveal(mpg) + shadow_wake(wake_length = 0.05)

shadow_wake() 降低

一种方法是复制每一帧所需的数据。 geom_density 应该看到每一帧中的所有内容,但是 geom_line 应该只“看到”当前显示值之前的值。我们可以使用 tidyr::uncount 复制我们的数据,然后为 geom_line 创建一个变量,当当前帧的值太高时,该变量为 NA。

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
)