How to show a change in axes and a change in rectangle dimensions using gganimate?

Viewed 141

I am trying to make an animation that shows a couple of rectangles changing shape, while the plotting axes change simultaneously. In the code below I have specified only two data states for the data to transition between, yet there appear to be three animated states: 1. The starting state 2. A state where the rectangle dimensions change 3. A state where the axes change. How can I make the axes change and rectangles change at the same time? A reproducible example and the resulting image are below.

library(tidyverse)
library(gganimate)

d <- tibble(
  x1 = c(1, 3, 1, 5, 4), 
  x2 = c(2, 4, 3, 6, 6), 
  y1 = c(1, 1, 4, 1, 3), 
  y2 = c(2, 2, 5, 3, 5), 
  t = c('a', 'a', 'a', 'b', 'b'), 
  r = c(1, 2, 3, 4, 5)
)

d <- bind_rows(
  d %>% mutate(Time = 1),
  d %>% 
    mutate(Time =2, x1 = x1 / 2, x2 = x2 / 2)
)
  
ggplot() + 
  scale_x_continuous(name="x") + 
  scale_y_continuous(name="y") +
  geom_rect(data=d, mapping=aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2, fill=t), color="black", alpha=0.5) +
  geom_text(data=d, aes(x=x1+(x2-x1)/2, y=y1+(y2-y1)/2, label=r), size=4) +
  transition_states(Time) + 
  view_step_manual(xmin = c(1, -6),
                   xmax = c(6, 12),
                   ymin = c(1, -5),
                   ymax = c(5, 10))

rectangles

0 Answers
Related