Add or override aes in the existing mapping object

♀尐吖头ヾ 提交于 2019-11-30 03:51:40

问题


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.


回答1:


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:



来源:https://stackoverflow.com/questions/21748598/add-or-override-aes-in-the-existing-mapping-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!