将tweenr和gganimate与条形图一起使用

时间:2019-06-07 02:17:08

标签: r gganimate

如何使用tweenr和gganimate在下面的两个条形图之间创建非常平滑的动画?

library(tweenr)
library(gganimate)
library(tidyverse)

df <- tibble(
  decile = c("lowest", "second", "third", "lowest", "second", "third"),
  change = c(1, 2, -0.5, -2, -3, 4),
  year = c(2001L, 2001L, 2001L, 2002L, 2002L, 2002L)
)

df2001 <- filter(df, year == 2001)
df2002 <- filter(df, year == 2002)

ggplot(df2001, aes(x = decile, y = change)) +
  geom_col() +
  scale_y_continuous(limits = c(-5, 5)) +
  theme_minimal()

ggplot(df2002, aes(x = decile, y = change)) +
  geom_col() +
  scale_y_continuous(limits = c(-5, 5)) +
  theme_minimal()

1 个答案:

答案 0 :(得分:3)

编辑:更改了transition_statesease_aes,以花更多时间进行过渡,增加了字体大小,并更改了animate术语,以使持续时间更长且移动速度更慢。

a <- ggplot(df, aes(x = decile, y = change/2, 
                    height = change, width = 0.9, group = decile)) +
  geom_tile() +
  scale_y_continuous(limits = c(-5, 5), name = "change") +
  theme_minimal(base_size = 16) +
  transition_states(year, wrap = T, transition_length = 10, state_length = 1) +
  ease_aes("cubic-in-out")

animate(a, fps = 30, duration = 10, width = 500, height = 300)
# Use up to two of fps, nframes, and duration to define the
#   length and frame rate of the animation.

enter image description here


请注意,我在上面使用geom_tile是因为geom_col在过渡时产生了这种非常规的行为。我怀疑绘制的geom_col不能在基线和范围之间进行区分,而在最小值和最大值之间进行区分,从而导致“滑动”动画。 (好奇是否其他人会看到更简单的解决方法。)

a <- ggplot(df, aes(x = decile, y = change)) +
  geom_col() +
  ...

enter image description here