Add or override aes in the existing mapping object

ggally, ggplot2, r

Solution

Based on @koshke's comment, here's a working example that does the job:

df <- data.frame(x=1:5, y=1, new_y=5:1, col=1:5, new_col=factor(1:5))
mapping <- aes(x=x, y=y, col=col)
ggplot(df, mapping) + geom_point(size=10)

add_modify_aes <- function(mapping, ...) {
  ggplot2:::rename_aes(modifyList(mapping, ...))  
}

ggplot(df, add_modify_aes(mapping, aes(color=new_col, y=new_y))) + geom_point(size=10)

There's a slight modification that deals with aes collisions (i.e., `col`, `color`, `colour`).

Initial plot: Modified plot:

Problem

Here's the minimal case: ``` df <- data.frame(x=1:5, y=1, col=1:5) mapping <- aes(x=x, y=y) ggplot(df, mapping) + geom_point(size=10) ``` Now I want to add (or overwrite) another aesthetic (colour) to the existing `mapping` object. The desired plot is ``` ggplot(df, aes(x=x, y=y, colour=col)) + geom_point(size=10) ``` I'm sure there exists a convenience function for this, but it is not listed in the documentation, and browsing the source didn't help either. I once seem to have stumbled upon something like `AddOrOverrideAes`, but no idea where exactly. Here's what my current solution is: ``` add_aes <- function (mapping, ...) { new_aes <- structure(append(mapping, as.list(match.call()[-(1:2)])), class = "uneval") rename_aes(new_aes) } environment(add_aes) <- asNamespace("ggplot2") ggplot(df, add_aes(mapping, colour=col)) + geom_point(size=10) ``` It works ok for addition, but not for overwriting (no check if this aes already exists, etc). Am I reinventing the wheel? The motivation for this is GGally's `ggpairs` customization, see this question. Edit: The workflow is as follows: get the existing `mapping` as a parameter, modify it in place and pass further to another function. I am not able to modify the "final" ggplot call.

Original source

Related problems