Search code examples
rgganimate

How to make a shadow_mark without interpolating points?


How can I create an animation that 1. adds new points to the plot at a time proportional to the measurement time, and 2. fades out older points over time?

I thought maybe I could achieve this with the following code:

library(tidyverse)
library(gganimate)
set.seed(1)

ex =
expand.grid(x = seq(0, 1, 0.2),
            y = seq(0, 1, 0.2),
            t = seq(0, 10, 1)) %>%
  as_tibble() %>%
  mutate(z = rnorm(x, mean = t, sd = 0.2))

ggplot(data = ex,
       mapping = aes(x, y, color = z)) +
  geom_jitter(position = position_jitter(width = 0.02, height = 0.02)) +
  transition_time(t) +
  scale_color_viridis_c() +
  shadow_mark(alpha = 0.4, size = 1)

generated animation

However, this plot interpolates the position of the point across time. While this makes sense to do for reproducing gapminder, it doesn't seem to be the effect I'm looking for: I want the same thing, but with no moving balls. I just want them to appear and then to fade out. But I'm wondering if there is a nice way to do this using the grammar?


Solution

  • Watching Thomas's talk on A Grammar of Visualization I saw in his ggraph example that, yes, he had my problem in mind when formulating the grammar.

    ggplot(data = ex,
           mapping = aes(x, y, color = z)) +
      geom_jitter(position = position_jitter(width = 0.02, height = 0.02)) +
      transition_events(start = t, 
                        enter_length = 1,
                        exit_length = 4) +
      scale_color_viridis_c() +
      enter_fade() +
      exit_fade()
    

    proposed solution