首页 > 解决方案 > gganimate:动画 alpha 不适用于 transition_reveal?

问题描述

我正在尝试重新创建这个:https ://rpubs.com/dgrtwo/valentine

这是他的旧 gganimate API 代码:

library(dplyr)
library(tidyr)
library(broom)
library(ggplot2)
library(gganimate)

d <- data_frame(t = seq(-pi, 0, .01),
                x1 = 16 * (sin(t)) ^ 2,
                x2 = -x1,
                y = 13 * cos(t) -
                  5 * cos(2 * t) -
                  2 * cos(3 * t) -
                  cos(4 * t)) %>%
  gather(side, x, x1, x2)

heart <- d %>%
  inflate(t1 = max(d$t) + seq_len(20)) %>%
  arrange(((side == "x2") - 1) * t)

g <- ggplot(d, aes(x, y, frame = round(t, 1))) +
  geom_path(aes(cumulative = TRUE, group = side)) +
  geom_polygon(aes(alpha = t1, frame = t1), data = heart, fill = "red", show.legend = FALSE) +
  geom_text(aes(x = 0, y = 0, label = "Happy Valentine's Day", alpha = t1, frame = t1),
            data = heart, size = 8, color = "white", show.legend = FALSE) +
  coord_equal() +
  theme_bw()

s <- gg_animate(g, interval = .1,
                title_frame = FALSE)

在此处输入图像描述

这是我更新代码的最佳尝试

library(dplyr)
library(tidyr)
library(ggplot2)
library(gganimate)
library(transformr)
library(gifski)

d <- tibble(t      = seq(-pi, 0, .01),
            x1     = 16 * (sin(t)) ^ 2,
            x2     = -x1,
            y      = 13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t),
            alphas = -100
          ) %>% gather(side, x, x1, x2)

max_t <- max(d)$t)
last_frame = filter(d, t = max_t)
extra_frames = tibble(t      = max_t + seq(0, 1.99, .01),
                      y      = first(last_frame$y),
                      side   = rep(last_frame$side, 100),
                      x      = rep(last_frame$x, 100),
                      alphas = t * 2
                    )

heart <- bind_rows(d, extra_frames) %>% arrange(((side == "x2") - 1) * t)

g <- ggplot(d, aes(x, y)) +
  geom_line(aes(group = side)) +
  geom_polygon(aes(alpha = alphas), data = heart, fill = "red", show.legend = FALSE) +
  geom_text(aes(x = 0, y = 0, label = "Happy Valentine's Day", alpha = alphas),
            data = heart, size = 8, color = "white", show.legend = FALSE) +
  coord_equal() +
  guides(alpha = F) +
  theme_bw() + transition_reveal(t)

animate(g, renderer = gifski_renderer())

在此处输入图像描述 由于您无法使用新 API (GRRRR) 为不同的几何图形提供不同的帧,因此我alphas在构建心脏时添加了一个应该为 0(或 -100 bc 我感到沮丧)的列,然后我添加了额外的行到heartwheretalphas增量,但其余值保持不变。

这应该有效吗?感觉它与transition_reveal 有关?我还注意到这对 DF 的顺序很敏感,这是我没想到的?任何帮助将不胜感激,因为我想在情人节发送这个!

标签: rggplot2gganimate

解决方案


推荐阅读