gganimate 条形图:替换条形图时平滑过渡

JSP*_*JSP 5 animation r bar-chart ggplot2 gganimate

我想用这个gganimate包创建一个动画条形图。条形图应包含 4 个条形,但应同时显示其中的三个条形。当一根柱线脱落而新柱线出现时,动画应该是平滑的(就像两个柱线在图中切换位置时一样)。

考虑以下示例:

# Set seed
set.seed(642)

# Create example data
df <- data.frame(ordering = c(rep(1:3, 2), 3:1, rep(1:3, 2)),
                 year = factor(sort(rep(2001:2005, 3))),
                 value = round(runif(15, 0, 100)),
                 group = c(letters[sample(1:4, 3)],
                           letters[sample(1:4, 3)],
                           letters[sample(1:4, 3)],
                           letters[sample(1:4, 3)],
                           letters[sample(1:4, 3)]))

# Load packages
library("gganimate")
library("ggplot2")

# Create animated ggplot
ggp <- ggplot(df, aes(x = ordering, y = value)) +
  geom_bar(stat = "identity", aes(fill = group)) +
  transition_states(year, transition_length = 2, state_length = 0)
ggp
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

如果更换了一个酒吧,酒吧的颜色只是改变,没有任何平滑的动画(即新的酒吧应该从侧面飞入,替换的酒吧应该飞出)。

问题:我怎样才能顺利更换钢筋?

Jon*_*ing 5

我在 2003 年遇到了一些小故障(b 和 c 似乎在转换时交换了),但希望这可以帮助您更接近。我认为enter_drift并且exit_drift是您正在寻找的。

library("gganimate")
library("ggplot2")
ggp <- ggplot(df, aes(x = ordering, y = value, group = group)) +
  geom_bar(stat = "identity", aes(fill = group)) +
  transition_states(year, transition_length = 2, state_length = 0) + 
  ease_aes('quadratic-in-out') +   # Optional, I used to see settled states clearer
  enter_drift(x_mod = -1) + exit_drift(x_mod = 1) +
  labs(title = "Year {closest_state}")
animate(ggp, width = 600, height = 300, fps = 20)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明