Search code examples
rggplot2gganimate

Labeling Dates In gganimate


Let's say we have the following dataframe:

> df
  date number
1   9/1      1
2   9/2      2
3   9/3      3
4   9/4      4
5   9/5      5

, where the 'date' column has a "month/date" format.

Based on this data, I want to make an animation which has the same "month/date" format in the 'date' column in the x-axis.

However, R throws out an error message that the 'date' column must be a finite number. So I removed '/' in the 'date' column and it now works (see attached image) with the following code:

df <- data.frame("date" = c(91, 92, 93, 94, 95), "number" = c(1,2,3,4,5))

p <- ggplot(df, aes(x = date, y = number, group =1)) +
  geom_line() +
  geom_point() +
  transition_reveal(date)
p

However, how do I label the 'date' column in the x-axis of the animation such that it maintains the "month/date" format?


Solution

  • ggplot can handle dates, but they have to be of type date. Otherwise, ggplot can't know how to display them correctly. As far as I know, there is no method for having a date without Year. However, if your data consists of less than a year ggplot won't display the year but only month and day. Here is an example:

        library(ggplot2)
        library(gganimate)
        library(gifski)
    
        df <- data.frame("date" = c(91, 92, 93, 94, 95), "number" = c(1,2,3,4,5))
    
        df$date <- as.Date(c("2019-09-01", "2019-09-02", "2019-09-03", "2019-09-04", "2019-09-05"))
    
        p <- ggplot(df, aes(x = date, y = number, group =1)) +
          geom_line() +
          geom_point() +
          transition_reveal(date)
        p