I'm trying to create an animated time series plot using gganimate
. The following code produces almost the desired output. It creates two random time series, constructs a data frame and renders the desired animation:
# necessary packages
require(ggplot2)
require(gganimate)
require(transformr)
require(gifski)
# construct data frame with two random time series and time index t
TS = matrix(rnorm(100 * 2), 100, 2)
plot.df = data.frame(TS, t = 1:100)
plot.df = reshape2::melt(plot.df, id.vars = "t")
# usual ggplot line plot structure
p = ggplot(plot.df, aes(x = t, y = value, col = variable)) +
geom_line()
# animation that reveals time series along time dimension (= x-axis)
play = p + transition_reveal(t)
# render plot using gifski
animate(play,renderer = gifski_renderer())
In the output, both time series are revealed at the same time. Is there an option to first reveal the first time series and then reveal the second time series on top of the first one?
What about a workaround that could help. The idea is to create a new column that is a progressive from 1 to nrow
of the dataset and use it in the transition_reveal()
:
Obviously the dataset should be ordered by time and variabiles like in your data.
# necessary packages
require(ggplot2)
require(gganimate)
require(gifski)
# construct data frame with two random time series and time index t
TS <- matrix(rnorm(100 * 2), 100, 2)
plot.df <- data.frame(TS, t = 1:100)
plot.df <- reshape2::melt(plot.df, id.vars = "t")
# reorder in case
# plot.df <- plot.df[order(plot.df$variable,plot.df$t),]
# adding a new column to make progressive the reveal of the data
plot.df$transition_value <- 1:nrow(plot.df)
# your ggplot plot
p <- ggplot(plot.df, aes(x = t, y = value, col = variable)) +
geom_line()
# reveal with the new value
play <- p + transition_reveal(transition_value)
# render plot using gifski
animate(play,renderer = gifski_renderer())