在现有映射对象中添加或覆盖aes [英] Add or override aes in the existing mapping object
问题描述
df < - data.frame(x = 1:5,y = 1,
mapping< -aes(x = x,y = y)
ggplot(df,mapping)+ geom_point(size = 10)
$ c $现在我想在现有的映射
对象。所需的图是:
ggplot(df,aes(x = x,y = y,color = col))+ geom_point( size = 10)
我确定存在一个方便的函数,但没有列出在文档中,浏览源代码也没有帮助。我曾经似乎偶然发现过像 AddOrOverrideAes
这样的东西,但不知道在哪里。
以下是我目前的解决方案是:
add_aes< - function(mapping,...){
new_aes< - structure(append (映射,as.list(match.call()[ - (1:2)])),class =uneval)
rename_aes(new_aes)
}
环境(add_aes)< - asNamespace(ggplot2)
ggplot(df,add_aes(mapping,color = col))+ geom_point(size = 10)
pre>
它适用于添加,但不能覆盖(不检查这个aes是否已经存在等)。我是否重新发明了轮子?
这个动机是GGally的 ggpairs
自定义,请参阅
编辑
: 工作流程如下:获取现有的映射
作为参数,修改它放置并进一步传递给另一个功能。我无法修改最终ggplot调用。
基于@ koshke的评论,这里有一个工作示例作业:
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)
处理aes冲突(例如 col ,
color
,
color
)。
初始绘图:
修改过的图表:
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.
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:
这篇关于在现有映射对象中添加或覆盖aes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!