Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use same-named aesthetics by default with ggplot in R?

Tags:

r

ggplot2

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?

like image 803
logworthy Avatar asked May 24 '16 02:05

logworthy


2 Answers

aes_auto(), but it's deprecated apparently. Alternatively,

aes_all(names(rect))
like image 141
baptiste Avatar answered Oct 15 '22 23:10

baptiste


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()
like image 6
hrbrmstr Avatar answered Oct 16 '22 00:10

hrbrmstr