spsanderson / healthyR.ai

healthyR.ai - AI package for the healthyverse
http://www.spsanderson.com/healthyR.ai/
Other
16 stars 6 forks source link

Add function `hai_density_plot()` #146

Closed spsanderson closed 2 years ago

spsanderson commented 2 years ago
hai_density_plot <- function(.data, .dist_name_col, .value_col, 
                             .alpha = 0.382, .interactive = FALSE){

  # Tidyeval ----
  dist_name_var <- rlang::enquo(.dist_name_col)
  value_col_var <- rlang::enquo(.value_col)
  alpha <- as.numeric(.alpha)

  dnv_name <- rlang::quo_name(dist_name_var)
  vcv_name <- rlang::quo_name(value_col_var)

  # Checks ----
  if(rlang::quo_is_missing(dist_name_var) | 
     rlang::quo_is_missing(value_col_var)){
    rlang::abort(
      "All parameters must be supplied:
       * .dist_name_col
       * .value_col
       "
    )
  }

  if(!is.numeric(alpha) | (alpha > 1) | (alpha < 0)){
    rlang::abort("The .alpha parameter must be a number between 0 and 1")
  }

  # Data setup ----
  data_tbl <- tibble::as_tibble(.data) %>%
    dplyr::ungroup() %>%
    dplyr::select(
      {{dist_name_var}},
      {{value_col_var}}
    )

  # Plots ---
  plt <- ggplot2::ggplot(
    data = data_tbl,
    mapping = ggplot2::aes_string(vcv_name, color = dnv_name, group = dnv_name)
  ) +
    ggplot2::geom_density(alpha = .alpha) +
    ggplot2::theme_minimal() +
    ggplot2::labs(
      title = "Distribution Density Comparison",
      color = "Distribution",
      x = "",
      y = "Desnsity"
    ) +
    ggplot2::theme(legend.position = "bottom")

  if(.interactive){
    plt <- plotly::ggplotly(plt)
  }

  # Return ----
  return(plt)
}