Skip to main content

A time series that draws itself

Animation
transition_reveal() grows four stock-index lines along a Date column, with a smoothly advancing leading point and the date reached so far in the title.

transition_states() and transition_time() move marks between states. transition_reveal() does something else: it draws the data in, in the order of a variable. Each frame shows the rows reached so far, and a line grows through them with an interpolated leading point, so it advances smoothly between observations rather than jumping from one to the next.

The data is R’s EuStockMarkets, daily closing prices of four European indices from 1991 to 1998, thinned to one trading day in five and given real Dates.

step <- seq(1, nrow(EuStockMarkets), by = 5)
days <- as.Date("1991-01-01") +
  round((as.numeric(time(EuStockMarkets))[step] - 1991) * 365.25)

stocks <- data.frame(
  date  = rep(days, 4),
  index = rep(colnames(EuStockMarkets), each = length(step)),
  close = as.vector(EuStockMarkets[step, ])
)

range(stocks$date)
#> [1] "1991-07-01" "1998-08-19"
a <- vplot(stocks, width = 7, height = 3.6) |>
  mark_line(x = date, y = close, color = index) |>
  labs(title = "European stock indices, {format(frame_along, '%B %Y')}",
       x = NULL, y = "closing price") |>
  transition_reveal(date) |>
  animate(nframes = 120, fps = 20)

The 120 frames are spread evenly over the range of date, from July 1991 to August 1998. The title uses the frame variable {frame_along}, the along value reached by the frame, which keeps the class of the column: here a Date, so format() with a strftime pattern turns it into a month and a year. Any R expression works inside the braces.

Only the data layers are revealed. The panel, gridlines, axes and legend are drawn whole on every frame, and the scales are trained once over all the data and frozen, so the y axis already reaches 8 000 in 1991, and the late-1990s run-up is drawn against the same axis as the flat early years. A yearly break with a "%Y" label keeps the date axis to seven short labels.

Size

Each frame carries the lines revealed so far, so the file grows with the length of the series times the number of frames: here about 2 MB of SVG, around 40 KB once the server compresses it. Thinning a daily series to weekly, as above, is the main lever; a smaller nframes is the other.

Back to top