Skip to content

Instantly share code, notes, and snippets.

@carlbfrederick
Created July 10, 2018 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlbfrederick/5f7c389ae8d7f9bc4c2727c3140b827c to your computer and use it in GitHub Desktop.
Save carlbfrederick/5f7c389ae8d7f9bc4c2727c3140b827c to your computer and use it in GitHub Desktop.
4th attempt at clean plots for data documentation
#'dataMaid_cleanPlot.R
#'
#'These functions makes the default graphics prettier/easier to read:
#'
#' 1. Minimal Theme
#' 2. Angled Axis Text
#'
#' @example
cleanPlotHelper <- function(data, vnam, sideways) {
p <- ggplot(aes(x = mids, y = counts), data = data) +
geom_bar(stat = "identity") +
labs(x = vnam, y = "Frequency") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 30, hjust = 1))
if (sideways) {
p <- p + coord_flip()
}
return(p)
}
cleanPlot <- function(v, vnam, doEval = TRUE) {
sideways <- TRUE
if (length(unique(v)) > 20 && ("numeric" %in% class(v) | "integer" %in% class(v))) {
tmp <- hist(v, plot = FALSE)
tmp <- as.data.frame(tmp[c("mids", "counts")])
sideways <- FALSE
} else {
tmp <- data.frame("mids" = v) %>%
dplyr::group_by(mids) %>%
dplyr::count(.) %>%
dplyr::rename(counts = n)
}
if ((!is.ordered(tmp$mids) && is.factor(tmp$mids)) || is.character(tmp$mids)) {
tmp$mids <- forcats::fct_reorder(tmp$mids, tmp$counts)
}
thisCall <- call("cleanPlotHelper", data = tmp, vnam = vnam, sideways = sideways)
if (doEval) {
return(eval(thisCall))
} else {
return(deparse(thisCall))
}
}
cleanPlot <- visualFunction(cleanPlot,
description = "Cleaned Plots for Data Documentation",
classes = c("character", "factor", "labelled", "numeric", "integer", "logical", "Date"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment