gganimate: show label only for latest state

Viewed 445

I am trying to animate a scatter plot showing only the labels for the most recent dot.

What I am struggling with is to get the preceding labels disappear. I understand that 'closest_state' might be part of the answer, but as far as I can tell fading out preceding labels and keeping the preceding dots is not possible.

What I found is this, but I am struggling to implement it.

Any help? Many thanks!

library(tidyverse)
#> Warning: package 'dplyr' was built under R version 3.6.3
#> Warning: package 'forcats' was built under R version 3.6.3
library(gganimate)
#> Warning: package 'gganimate' was built under R version 3.6.2

ggplot(airquality %>% 
               filter(Month==5), 
             aes(Day, Temp)) +
  labs(title='{closest_state}')+
  geom_point(color='red', size=10) +
  geom_text(aes(label=paste("temp:", Temp, "\n", 
                        "day:", Day)),
            x=20,
            y=80,
            size=10)+
  transition_states(Day, state_length = 50)+
  shadow_mark(colour = 'black', size = 5)

Created on 2020-03-24 by the reprex package (v0.3.0)

1 Answers

I'm just a beginner in gganimate so this is probably not the simplest way and just a hack. But it works. Try this:

The basic idea is to get rid of the shadow marks. To show past values I use a inflated df, where obs are grouped into frames by splitting the df by Day, then accumulate Days to frames, ... Drawback. Besides infalting the df we have to do some additional data manipulation steps to get the colors and sizes right.

library(tidyverse)
library(gganimate)

df <- airquality %>% 
  filter(Month == 5) %>% 
  split(.$Day) %>% 
  accumulate(~ bind_rows(.x, .y)) %>% 
  bind_rows(.id = "frame") %>% 
  mutate(frame = as.integer(frame)) %>% 
  group_by(frame)  %>% 
  mutate(label = paste("temp:", last(Temp), "\n", "day:", last(Day)),
         color = ifelse(Day == last(Day), "red", "black"),
         size = ifelse(Day == last(Day), 10, 5)) %>% 
  ungroup()

ggplot(df) +
  labs(title = '{closest_state}') +
  geom_point(aes(Day, Temp, color = color, size = size)) +
  scale_color_identity() +
  scale_size_identity() +
  geom_text(aes(label = label), x=20, y=80, size=10)+
  transition_states(frame, state_length = 50)

Created on 2020-03-24 by the reprex package (v0.3.0)

Related