Closed spsanderson closed 2 years ago
ts_ava_plot <- function(.data, .date_col, .value_col){
# Tidyeval ---
date_col_var_expr <- rlang::enquo(.date_col)
value_col_var_expr <- rlang::enquo(.value_col)
# Checks ----
if(!is.data.frame(.data)){
stop(call. = FALSE, ".data is not a data.frame/tibble, please supply.")
}
if(rlang::quo_is_missing(date_col_var_expr) | rlang::quo_is_missing(value_col_var_expr)){
stop(call. = FALSE, "Both .date_col and .value_col must be supplied.")
}
# Data Manipulation ----
data_tbl <- tibble::as_tibble(.data) %>%
dplyr::select({{date_col_var_expr}},{{value_col_var_expr}})
data_diff_tbl <- data_tbl %>%
timetk::tk_augment_differences(.value = {{value_col_var_expr}}, .differences = 1) %>%
timetk::tk_augment_differences(.value = {{value_col_var_expr}}, .differences = 2) %>%
dplyr::rename(velocity = contains("_diff1")) %>%
dplyr::rename(acceleration = contains("_diff2")) %>%
tidyr::pivot_longer(-{{date_col_var_expr}}) %>%
dplyr::mutate(name = stringr::str_to_title(name)) %>%
dplyr::mutate(name = forcats::as_factor(name))
# Plot ----
g <- ggplot2::ggplot(
data = data_diff_tbl,
ggplot2::aes(
x = {{date_col_var_expr}},
y = value,
group = name,
color = name
)
) +
ggplot2::geom_line() +
ggplot2::facet_wrap(name ~ ., ncol = 1, scale = "free") +
ggplot2::theme_minimal() +
ggplot2::labs(
x = "Date",
y = "",
color = ""
) +
tidyquant::scale_color_tq()
# Return ----
return(g)
}