Search code examples
rggplot2gganimateggrepel

gganimate annotate a date variable that is not in the transition_states


Trying to create an animated chart using ggplot and gganimate where the x-axis (and transition_states value) is numeric, but a running date variable is overlaid on the chart as an annotation. The animation works, but it appears all of the dates in the time series are printed at once (all on top of each other) rather than corresponding to the animation. Also trying to keep a consistent ggrepel label above the geom_point. Here is a reprex:

library(dplyr)
library(lubridate)
library(ggrepel)
library(ggplot2)
library(gganimate)

a0 <- data.frame(dt = seq(ymd('2020-01-01'),ymd('2020-03-31'), by = '1 day'),
                 num = seq(1,91,by=1), val=seq(1,91,by=1), label = rep("x",91))

p <- ggplot(data=a0, aes(x=num, y=val, color=label)) +
  geom_point(size=10) +
  annotate("text",  x = 75, y = 75,
           label = as.Date(a0$dt), size = 10) +
  geom_text_repel(label=a0$label, size=10) +
  scale_x_continuous() +
  theme_minimal() +
  theme(text = element_text(size=30),
        legend.position = "none")

anim <- p + 
  transition_states(num,
                    transition_length = 10,
                    state_length = 1000)

anim

Solution

  • interesting problem.

    Check the geom_text line out below.

    p <- ggplot(data=a0, aes(x=num, y=val, color=label, group=num)) +
        geom_point(size=10) +
        geom_text(data=a0, aes(x=75, y=75, label=as.Date(a0$dt), size=10)) +
    scale_x_continuous() +
    theme_minimal() +
    theme(text = element_text(size=30),
        legend.position = "none")
    

    Hope it helps.