#' Stacked bar plot
#'
#' This function creates a stacked barplot. The data does not have to be preprocessed.
#'
#' @param df The raw data frame (tidy data). The counting happens in the function.
#' @param xcol The variable to be plottet on the x-axis
#' @param ycol The variable which
#' @param title The title as a string
#'
#' @return A ggplot2 object. Add more items with "+".
#' @export
#'
#' @examples
#' cat_stacked_barplot(mtcars %>% dplyr::mutate_all(as.character), am, gear)
cat_stacked_barplot <- function(df, xcol, ycol, title = ""){
xcol <- rlang::enquo(xcol)
ycol <- rlang::enquo(ycol) # Source = xcol, Priority = ycol
df_num <- df %>%
count(!!xcol)
df_plot <- df %>%
count(!!ycol, !!xcol)
df_plot %>%
ggplot2::ggplot(ggplot2::aes(x = forcats::fct_rev(!!xcol), y = n, fill = !!ycol)) +
ggplot2::geom_bar(stat = "identity", position = "stack", color="black") +
ggplot2::geom_text(data = df_num, ggplot2::aes(x = !!xcol, y = n, label = n, fill = NULL), nudge_y = 0.4) +
ggplot2::coord_flip() +
ggplot2::labs(title=paste(title),
x="",
y="Count",
fill="") +
ggplot2::scale_y_continuous(breaks = seq(0, max(df_num$n), round(max(df_num$n)/7) ) ) +
ggplot2::theme_light()
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.