spsanderson / healthyR.ts

A time-series companion package to healthyR
https://www.spsanderson.com/healthyR.ts/
Other
18 stars 3 forks source link

Make function `ts_tva_plot` #157

Closed spsanderson closed 2 years ago

spsanderson commented 2 years ago
data_tbl <- ts_alos_elos_query() %>%
  mutate(excess = performance - los) %>%
  select(dsch_date, excess) %>%
  mutate(dsch_date = as.Date(dsch_date)) %>%
  summarise_by_time(
    .date_var = dsch_date,
    .by   = "month",
    .type = "ceiling",
    N     = sum(excess, na.rm = TRUE)
  ) %>%
  mutate(dsch_date = dsch_date %>% subtract_time(period = "1 day")) %>%
  set_names("date_col","value")

data_tbl %>%
  tk_augment_differences(.value = value, .differences = 1) %>%
  tk_augment_differences(.value = value, .differences = 2) %>%
  rename(velocity = contains("_diff1")) %>%
  rename(acceleration = contains("_diff2")) %>%
  pivot_longer(-date_col) %>%
  mutate(name = str_to_title(name)) %>%
  mutate(name = as_factor(name)) %>%
  ggplot(aes(x = date_col, y = value, group = name, color = name)) +
    geom_line() +
  facet_wrap(name ~ ., ncol = 1, scale = "free") +
  theme_minimal() +
  labs(
    title = "Total Excess Days Trend, Velocity and Acceleration",
    x = "Date",
    y = "",
    color = ""
  ) +
  scale_color_tq()
spsanderson commented 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)

}