spsanderson / healthyR.ts

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

Create function for residuals vs actual plot `ts_skedacity_scatter_plot()` #180

Closed spsanderson closed 2 years ago

spsanderson commented 2 years ago

This plot should show the residuals on the y axis and the actual values on the x axis to check for hetero/homoskedacity

spsanderson commented 2 years ago

set a parameter .interactive to default to TRUE for a plotly plot.

spsanderson commented 2 years ago
ts_skedacity_scatter_plot <- function(.calibration_tbl, .model_id = NULL
                              , .interactive = FALSE){

  # * Tidyeval ----
  calibration_tbl  <- .calibration_tbl
  model_id         <- .model_id
  interactive_bool <- .interactive

  # * Checks ----
  if(!modeltime::is_calibrated(calibration_tbl)){
    stop(call. = FALSE, "You must supply a calibrated modeltime table.")
  }

  # Calibration Tibble filter
  if(is.null(model_id)){
    calibration_tbl <- calibration_tbl
  } else {
    calibration_tbl <- calibration_tbl %>%
      dplyr::filter(.model_id == model_id)
  }

  g <- calibration_tbl %>% 
    dplyr::ungroup() %>% 
    dplyr::select(-.model, -.type) %>% 
    tidyr::unnest(.calibration_data) %>% 
    ggplot2::ggplot(
      mapping = ggplot2::aes(
        x = .prediction
        , y = .residuals
        , fill = .model_desc
      )
    ) + 
    ggplot2::geom_point(alpha = 0.312) + 
    ggplot2::geom_smooth(alpha = 0.312, size = .5) +
    ggplot2::facet_wrap(
      ~ .model_desc
      , scales = "free"
    ) + 
    tidyquant::scale_color_tq() + 
    ggplot2::theme_minimal() +
    ggplot2::theme(legend.position = "none") +
    ggplot2::labs(
      title = "Skedacity Scatter Plot"
      , x = "Predictions"
      , y = "Residuals"
    )

  if(interactive_bool){
    g <- plotly::ggplotly(g)
  }

  return(g)

}