#' Generate a ggplot2 for a two factorial variables - target variable in the cross section of demographic variables.
#'
#' Function accepts target variables and demographic variables (factorial variables) and calculates the proportions of the target variable in the demographic variable cut.
#' The function produces a bar chart of the target variable proportion as a demographic variable function.
#'
#' Use '$' to generate the desired graph. See example.
#'
#'
#' @param x a tbl() with the data.
#' @param target_variable Target variable on which the demographic cuts will be made.
#' @param demographics Demographics variables. The variables' levels affect ordering on the x axis
#' @param arrange_desc Logical. arrange parameter.
#'
#' @return Function accepts target variables and demographic variables (factorial variables) and calculates the proportions of the target variable in the demographic variable cut.
#' The function produces a bar chart of the target variable proportion as a demographic variable function.
#'
#'
#' @examples
#' quality_assurance <- data.frame(
#' product_color = sample(c("Red", "Green", "Blue", "Orange"), size = 50, replace = T),
#' status = sample(c("pass", "fail"), size = 50, replace = T),
#' product_name = sample(c("Lea", "Rose", "Ruth"), size = 50, replace = T))
#'
#' quality_assurance_plot <- gg_prop_var_by_demographics(quality_assurance,
#' target_variable = product_name,
#' demographics = vars(product_color, status))
#'
#'quality_assurance_plot$product_color
#'quality_assurance_plot$status
#'
#' @importFrom magrittr %>%
#' @importFrom ggplot2 guides
#' @importFrom dplyr group_by
#' @importFrom dplyr enquo
#' @importFrom dplyr filter
#' @importFrom stringr str_remove
#' @importFrom purrr map
#'
#' @export
#'
gg_prop_var_by_demographics <- function(x,
target_variable,
demographics = vars(...),
arrange_desc = T){
all_plots <- map(demographics,
~{
target_var <- enquo(target_variable)
x %>%
group_by(!!.x) %>%
filter(!is.na(!!.x)) %>%
filter(!is.na(!!target_var)) %>%
saridr::gg_prop_plot(vari = {{target_variable}},
arrange_desc = arrange_desc) +
guides(fill=guide_legend(title=""))
})
names(all_plots) <- str_remove(as.character(demographics), "~")
return(all_plots)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.