Использование tweenr и gganimate с графиками - PullRequest
1 голос
/ 07 июня 2019

Как использовать 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 Ответ

3 голосов
/ 07 июня 2019

Редактировать: изменены 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.

enter image description here


Обратите внимание, я использовал geom_tile выше, потому что geom_col произвел это нестандартное поведение при переходе. Я подозреваю, что нарисованный geom_col не различает его базовую линию и его экстент, а скорее между его минимальным и максимальным, что приводит к «скользящей» анимации. (Любопытно, если другие увидят более легкий обходной путь.)

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

enter image description here

...