Created
October 16, 2018 03:22
-
-
Save boshek/6ad055d6d8ab8294bc050eb245fa18b3 to your computer and use it in GitHub Desktop.
Animate a hydrograph in a circle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## based on this code: https://twitter.com/JustTheSpring/status/1049468485334523906 | |
library(tidyverse) | |
library(lubridate) | |
library(gganimate) | |
library(tidyhydat) | |
stn <- "08MF005" | |
flow_data <- hy_daily_flows(stn, start_date = "2012-01-01", end_date = "2016-12-31") %>% | |
filter(!is.na(Value)) %>% | |
select(date = Date, value = Value) | |
title <- paste0(hy_stations(stn)$STATION_NAME, " (", | |
hy_stations(stn)$STATION_NUMBER, ")") | |
frame_count <- (max(flow_data$date) - min(flow_data$date))/ lubridate::ddays(1) | |
cycle_length <- 365 | |
animation_df <- map_df(seq_len(frame_count), ~flow_data, .id = "id") %>% | |
mutate(id = as.integer(id)) %>% | |
mutate(view_date = min(flow_data$date) + id - 1) %>% | |
filter(date <= view_date) %>% | |
mutate(days_ago = (view_date - date)/ ddays(1), | |
phase_dif = (days_ago %% cycle_length) / cycle_length, | |
x_pos = -sin(2*pi * phase_dif), | |
nearness = cos(2*pi * phase_dif), | |
year = factor(year(date))) | |
b <- ggplot(animation_df) + | |
geom_path(aes(x_pos, value, alpha = nearness, colour = year, size = -days_ago)) + | |
scale_size(range = c(0,2)) + | |
transition_manual(id) + | |
scale_colour_viridis_d(name = "Year") + | |
labs(title = title, caption = "Data from HYDAT accessed via tidyhydat package", | |
y = "Discharge (m^3/s)", x = "") + | |
theme_minimal() + | |
guides(size = "none", alpha = "none") + | |
theme(axis.text.x = element_blank()) | |
animate(b, fps = 25, duration = 15, width = 600, height = 600) | |
anim_save("circular_hydrograph.gif") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment