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.