Animated Cat Time Series

Sometimes (all the time?) it’s fun to be a bit absurd with data visualization.

Fortunately, the R ecosystem makes that very easy.

There’s a ggcats package out there that allows MEME CATS to be overlaid on ggplot2 visualizations.

There are plenty of ways to put ggcats to good use. In this instance, I’ve chosen to use it with time series data, specifically stock prices. We’ll make it extra fun with some animation.

As always, let’s first load up some packages.

library(tidyverse)
library(gganimate)
library(ggcats) # remotes::install_github("R-CoderDotCom/ggcats@main")
library(hrbrthemes)
library(tidyquant)
library(gifski)

Then, pick a stock. Let’s arbitrarily look at Tesla (ticker symbol TSLA).

symbol <- "TSLA"

We’ll use the tidyquant package to source the data from Yahoo Finance.

stock <- tidyquant::tq_get(symbol, get = "stock.prices", from = "2022-01-01", to = Sys.Date())
head(stock)
## # A tibble: 6 × 8
##   symbol date        open  high   low close    volume adjusted
##   <chr>  <date>     <dbl> <dbl> <dbl> <dbl>     <dbl>    <dbl>
## 1 TSLA   2022-01-03  383.  400.  379.  400. 103931400     400.
## 2 TSLA   2022-01-04  397.  403.  374.  383. 100248300     383.
## 3 TSLA   2022-01-05  382.  390.  360.  363.  80119800     363.
## 4 TSLA   2022-01-06  359   363.  340.  355.  90336600     355.
## 5 TSLA   2022-01-07  360.  360.  337.  342.  84164700     342.
## 6 TSLA   2022-01-10  333.  353.  327.  353.  91815000     353.

Now we’ll put together the animation, focused on close price.

# TODO: get this part working
# prep_stock <- stock %>%
#    select(date, close) %>%
#    mutate(cat_col = rep(c("pop_close", "pop"), times = nrow(stock)/2, each = 1))

stock_anim_cat <- stock %>%
   ggplot(aes(x = date, y = close)) +
   geom_line(size = 2) +
   geom_cat(aes(cat = "pop"), size = 4) + # I was hoping to use the cat_col, but something's wonky
   scale_x_date(date_breaks = "1 month", date_labels = "%b") +
   scale_y_continuous(breaks = seq(0,2000,100)) +
   theme_ipsum_rc() +
   labs(
      title = sprintf("%s 2022 up to Meow", symbol),
      x = "Date",
      y = "Closing Price",
      caption = "kwanlin.com"
   ) +
   transition_reveal(date)
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
animate(stock_anim_cat, duration = 10, fps = 20, width = 800, height = 800, renderer = gifski_renderer())

We can save the animation as well:

anim_save("output.gif")

Resources #

There are some quirks to saving the gganimate output.

Some pointers: