gganimate slides points on x axis only

I'm trying to build some teaching illustrations that illustrate how we sort points to build the emperical cumulative distribution function (ECDF). I thought it would be nifty to use gganimate to show the points sliding from an unsorted state into a sorted state. I'm new to gganimate so I pulled up some examples and gave it a go.

Below is my first attempt. I created a data frame that contains an unsorted set of points. I tagged these sort_group=1 then I sort the points and assign new sort_order and set sort_group=2 in the data. I thought this would allow me to transition on sort_group to go from the unsorted to the sorted.

library(gganimate)
library(tidyverse)

df <- tibble(vals = rnorm(100), key = 1:100) %>% 
  mutate(sort_order = row_number(), sort_group=1) 

df %>%
  bind_rows(df %>% arrange(vals) %>% mutate(sort_order = row_number(), sort_group=2)) ->
  combined_data


ggplot(combined_data) +
  aes(x = vals, y = sort_order, color=key) +
  geom_point() +
  theme_bw() +
  transition_time(sort_group) +
  ease_aes('linear')  ->
  p

animate(p, nframes = 75, renderer = gifski_renderer("gganim.gif"))

gganim

There's a problem with the above though... the dots are sliding along the x axis as if their vals are changing. But each point keeps the same key and the same vals but gets a new sort_order. So I would expect the see the points sliding vertically, some slide up, others down, into their new sort orders.

I'm quite sure the problem is that I am missing some basic concept of ggamimate but I can't figure out what I'm doing wrong. Any tips?

I think you only have to combined_data <- arrange(combined_data,key)
to get
gganim

1 Like

From the help page of transition_time

The group aesthetic, if not set, will be calculated from the interaction of all discrete aesthetics in the layer (excluding label ), so it is often better to set it explicetly when animating, to make sure your data is interpreted in the right way. If the group aesthetic is not set, and no discrete aesthetics exists then all rows will have the same group.

Therefore, in the above example it appears to be grouping by the row number within sort_order 1 and 2. Since sort_order 2 is arranged by vals, that is why the points appear to be changing their val (and key). The most explicit specification of group in this example would be:

ggplot(combined_data) +
  aes(x = vals, y = sort_order, color = key, group = interaction(vals,key)) +
  geom_point() +
  theme_bw() +
  transition_time(sort_group) +
  ease_aes('linear') ->
  p

However since vals and key are one-to-one, specifying either or would also give the correct grouping.

2 Likes

wow that's shocking to me that this works! Do you understand why? I don't think I do. Somehow the sorting is giving gganimate a clue?

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.