Sometimes with ggplot I find myself using data frames where the variable names actually correspond to the aesthetics I want to use. Which leads to code like this:
rect <- data.frame(xmin=1,xmax=10,ymin=1,ymax=10)
ggplot(rect, aes(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax))+geom_rect()
Feels a bit WET.
Is there a way to avoid this repetition?
aes_auto()
, but it's deprecated apparently. Alternatively,
aes_all(names(rect))
UPDATE: See @baptiste's answer. This is 75% of the functionality of the (now deprecated) aes_auto()
.
An even more shortcut-but-data.frame
-specific alternative to the #spiffy solution by @MrFlick:
#' Generate ggplot2 aesthetic mappings from data.frame columns
#'
#' Use this like you would \code{aes()} or \code{aes_string()} but
#' pass in the \code{data.frame} you want to use for the mapping.
#' By default this will use all the column names from the input
#' \code{data.frame} so use column selections if you don't want
#' to map them all.
#'
#' @param df data.frame
aes_from_df <- function(df) {
mapping <- setNames(as.list(colnames(df)), colnames(df))
mapping <- lapply(mapping, function(x) {
if (is.character(x)) parse(text = x)[[1]] else x
})
structure(ggplot2:::rename_aes(mapping), class="uneval")
}
rect <- data.frame(xmin=1, xmax=10, ymin=1, ymax=10)
ggplot(rect, aes_from_df(rect)) + geom_rect()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With