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

时间:2019-02-12 18:21:29

标签: r animation ggplot2 bar-chart gganimate

我想用gganimate包创建一个动画的barplot。该条形图应包含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

enter image description here

如果交换了一个条,则条的颜色会改变而不会产生任何平滑的动画(即新条应从侧面飞入,而替换后的条应飞出)。

问题:如何使条形的更换更顺畅?

1 个答案:

答案 0 :(得分:1)

我在2003年出现了一些小故障(b和c在过渡时似乎互换了),但是希望这可以帮助您更紧密地联系。我认为enter_driftexit_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)

enter image description here