将 tweenr 和 gganimate 与条形图结合使用
Using tweenr and gganimate with bar plots
如何使用 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()
编辑:更改 transition_states
和 ease_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.
请注意,我在上面使用了 geom_tile
,因为 geom_col
在转换时产生了这种非常规行为。我怀疑绘制的 geom_col
不区分其基线和范围,而是区分其最小值和最大值,从而导致 "sliding" 动画。 (好奇其他人是否看到更简单的解决方法。)
a <- ggplot(df, aes(x = decile, y = change)) +
geom_col() +
...
如何使用 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()
编辑:更改 transition_states
和 ease_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.
请注意,我在上面使用了 geom_tile
,因为 geom_col
在转换时产生了这种非常规行为。我怀疑绘制的 geom_col
不区分其基线和范围,而是区分其最小值和最大值,从而导致 "sliding" 动画。 (好奇其他人是否看到更简单的解决方法。)
a <- ggplot(df, aes(x = decile, y = change)) +
geom_col() +
...