0

I'm trying to animate a plot I have where the X axis is non-numeric. The plot itself looks great, but I get a few error messages trying to animate it using the transition_reveal function.

I've got a data set called df100m that tracks the times/speeds of 10 meter splits of the 100 meter dash for various Olympic runners. It looks like this.

splits runners times(s) speed(mph)
10-20 Bolt_08 1.070 21.93
20-30 Bolt_08 0.910 24.58

84 more rows of different splits and runners omitted for space.

Plotting the average speed for this data set using stat_smooth looks great. I removed the reaction time (RT), the final time (TOTAL), and the starting 10m (Start-10), so that it only shows the numeric splits. Here is the code for the plot I have so far:

df100m %>% 
  filter(!grepl("RT", splits)) %>% 
  filter(!grepl("TOTAL", splits)) %>% 
  filter(!grepl("Start-10", splits)) %>% 
  ggplot(mapping = aes(x = splits, y = speed, col = runner, group = runner)) +
  stat_smooth(method = loess, se = F, fullrange = F) +
  theme(axis.text.x = element_text(angle = 90)) +
  theme(aspect.ratio = 3/7) +
  theme_solarized_2(light=F)

However when I add +transition_reveal(~splits) I get the following error message:

Error in seq.default(range[1], range[2], length.out = nframes) : 
  'from' must be a finite number
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf

Playing around with it, I sometimes also get the "invalid 'times' argument" error.

I know there are a few problems with the X axis (splits), it's a character rather than numeric, but also has a dash (-). I've seen a few posts attempting to fix this error, but I am unable to fix it as I am a beginner. Could someone point me to the right direction?

1 Answers1

1

Using some minimal made-up data, this is one possible approach creating the smoothed lines before the plotting, then basing the transition_reveal on the splits mutated to integers (as splits_int).

library(tidyverse)
library(gganimate)
library(broom)

tribble(~splits, ~speed, ~runner,
        "10-20", 20.0, "A",
        "20-30", 21.0, "A",
        "30-40", 22.0, "A",
        "10-20", 19.0, "B",
        "20-30", 20.0, "B",
        "30-40", 21.0, "B"
        ) %>% 
  mutate(splits_int = factor(splits) %>% as.integer()) %>% 
  nest(data = -runner) %>% 
  mutate(
    lm_model = map(data, ~loess(speed ~ splits_int, data = .x)),
    augmented = map(lm_model, augment) %>% map(select, .fitted)
    ) %>%
  unnest(c(augmented, data)) %>% 
  ggplot(aes(splits, .fitted, col = runner, group = runner)) +
  geom_line() +
  transition_reveal(splits_int)

Created on 2022-12-10 with reprex v2.0.2

Carl
  • 4,232
  • 2
  • 12
  • 24