gganimate 条形图:替换条形图时平滑过渡
gganimate barchart: smooth transition when bar is replaced
我想用 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
如果交换了一个条,条的颜色只是改变了,没有任何流畅的动画(即新的条应该从侧面飞进来,被替换的条应该飞出去)。
问:如何让柱线的更换更顺畅?
我在 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)
我想用 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
如果交换了一个条,条的颜色只是改变了,没有任何流畅的动画(即新的条应该从侧面飞进来,被替换的条应该飞出去)。
问:如何让柱线的更换更顺畅?
我在 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)