Skip to content

Instantly share code, notes, and snippets.

@alex-gable
Last active December 23, 2021 01:15
Show Gist options
  • Save alex-gable/35abb235e51eea9726cfc9f20e695b34 to your computer and use it in GitHub Desktop.
Save alex-gable/35abb235e51eea9726cfc9f20e695b34 to your computer and use it in GitHub Desktop.
year over year for daily time series with ggplot (hack)
library(tidyverse)
library(lubridate)
# also uses quantmod, zoo, sfthemes, janitor
# less noisy
options("getSymbols.warning4.0" = FALSE)
# example daily time series for multiple years
goog_price <- quantmod::getSymbols(Symbols = "GOOG",
auto.assign = FALSE) %>%
zoo::fortify.zoo() %>%
as_tibble() %>% janitor::clean_names() %>%
rename(date = index) %>%
rename_with(~ str_remove(.x, "^goog_")) %>%
mutate(year = as_factor(year(date)),
doy = yday(date))
# doy to month start date, will be funky on leap years but w/e
doy_labels <- tibble(
x = seq(as_date("2021-01-01"),
by = "month", length.out = 12),
month_label = month(x, label = T),
doy = yday(x)
)
yoy_goog_price <- goog_price %>%
filter(year(date) %in% 2019:2021) %>%
ggplot(aes(doy, open,
group = year,
colour = year)) +
geom_line() +
scale_x_continuous(breaks = doy_labels$doy,
labels = doy_labels$month_label) +
scale_y_continuous(labels = scales::dollar_format()) +
labs(x = "Date", y = "Open Price",
title = "Daily Google Open Price")
yoy_goog_price +
sfthemes::theme_sf_light() +
theme(
axis.title.x = element_text(hjust=0.5),
axis.title.y = element_text(hjust=0.5)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment