Search code examples
rggplot2gganimate

How to create smooth transition between states in gganimate using geom_point?


I am trying to create an animated plot using gganimate.
When I pass the following factor dat$period to transition_states,
I get 3 static images. I would prefer to have the points "move" from state-to- state.

Here is my code:

plot <-
          ggplot(data = dat, aes(x = age, y = value, color = period)) +
          geom_point(size = 3, aes(group = period)) +
          facet_wrap(~group)+
          transition_states(states=period, transition_length = 2, state_length = 1) +
          ease_aes('linear')+
          enter_fade()+
          exit_fade()

plot

Here is my data:

   record period value age group
1       1  start    45  24     a
2       2  start     6  22     c
3       3  start    23  32     b
4       4  start    67  11     a
5       1 middle    42  24     a
6       2 middle    65  22     c
7       3 middle    28  32     b
8       4 middle    11  11     a
9       1    end    23  24     a
10      2    end    14  22     c
11      3    end    34  32     b
12      4    end    21  11     a
13      5  start     5  12     c
14      6  start     9  23     c
15      7  start    53  47     b
16      8  start    17  32     a
17      5 middle    15  12     c
18      6 middle     6  23     c
19      7 middle    23  47     b
20      8 middle    67  32     a
21      5    end    51  12     c
22      6    end    16  23     c
23      7    end     8  47     b
24      8    end    41  32     a

The points appear/disappear - I would like the points to travel on the screen between states - any help appreciated


Solution

  • The group aesthetic is used to determine which rows in each period's data are treated as the same objects. You need group = record here:

    ggplot(data = dat, aes(x = age, y = value, color = period)) +
        geom_point(size = 3, aes(group = record)) +
        facet_wrap(~ group)+
        transition_states(states=period, transition_length = 2, state_length = 1) +
        ease_aes('linear')+
        enter_fade()+
        exit_fade()
    

    enter image description here