Search code examples
rggplot2tweengganimate

tweenr/gganimate with time series line plot


first I created an animated plot for a very simple time series line plot… Some example data:

library(dplyr)
library(gganimate)
library(tweenr)

data <- tribble(
  ~year, ~num,
  1950, 56,
  1951, 59,
  1952, 64,
  1953, 67,
  1954, 69,
  1955, 74,
  1956, 78,
  1957, 83
)

dat_ani <- data %>% 
  ggplot(aes(x = year, y = num, frame = year, cumulative = TRUE)) +
  geom_path() +
  geom_point()

gganimate(dat_ani)

so, just using gganimate is fine but I want to go a bit further by using tweenr for smoother transitions.

Knowing how tweenr uses interpolation I want a data frame similar to above but looks closer to this (just looking at in between 1950 and 1951):

data2 <- tribble(
  ~year, ~num,
  1950.0, 56.0,
  1950.1, 56.3,
  1950.2, 56.6,
  1950.3, 56.9,
  1950.4, 57.2,
  1950.5, 57.5,
  1950.6, 57.8,
  1950.7, 58.1,
  1950.8, 58.4,
  1950.9, 58.7,
  1951.0, 59.0,
)

but with all the other interpolated years and data points. I tried another way with tween_elements() function but that didn’t work (I think because x, time, and id were all the same variable…).

I am stumped on how to create a list of these data frames to use as the input for the tween_states() function. I’ve tried:

df_fun <- function(i) {
  dat <- data %>% subset(data$year[i])
  return(dat)
}

df_list <- purrr::map(seq(1950, 1957, by = 0.2), df_fun)

tween_data <- tween_states(df_list, tweenlength = 2, statelength = 3, 
                                             ease = "linear", nframes = 200)

among other attempts but of course this doesn’t work as there is no year == 1950.2, 1950.4, etc. in the original data frame…

any help would be appreciated!


Solution

  • if anybody else is interested, I posted in RStudio Community and was able to find an answer there:

    https://community.rstudio.com/t/tweenr-gganimate-with-line-plot/4027/5?u=r-by-ryo

    library(tidyverse)
    
    data <- tribble(
      ~year, ~num,
      1950, 56,
      1951, 59,
      1952, 64,
      1953, 67,
      1954, 69,
      1955, 74,
      1956, 78,
      1957, 83
    )
    
    dat_ani <- map(seq(nrow(data)), ~data[c(seq(.x), rep(.x, nrow(data) - .x)), ]) %>% 
        tweenr::tween_states(5, 2, 'cubic-in-out', 100) %>% 
        ggplot(aes(year, num, frame = .frame)) + 
        geom_path() + 
        geom_point()
    
    animation::ani.options(interval = 0.05)    # speed it up
    gganimate::gganimate(dat_ani, title_frame = FALSE)
    

    The map call makes a list with a data frame for each row, of the same number of observations as data, but with the rows yet to be displayed replaced with the last displayed row. Now tweenr::tween_states can track where each point is supposed to be moving, which lets it interpolate smoothly.

    credits to to alistaire on the RStudio Community forum!