R ggplot修改映射aes



我试图动态更新ggplot对象的映射,但不知道如何进行。

stackoverflow的另一篇帖子似乎解决了大部分问题,但我不知道如何命名aes映射。。。

# start of mapping:
mapping <- aes(x = X, y = Y, col = COLOUR)

这给出:

> mapping
Aesthetic mapping: 
* `x`      -> `X`
* `y`      -> `Y`
* `colour` -> `COLOUR`

然后,我想添加更多到aes函数的映射。

# new things that I want to add to mapping:
new_mapping_names <- letters[1:4]
# function that gets most of the way there:
#   fun from: https://stackoverflow.com/questions/21748598/add-or-override-aes-in-the-existing-mapping-object
add_modify_aes <- function(mapping, ...) {
ggplot2:::rename_aes(modifyList(mapping, ...))  
}
# loop to try add them in one by one:
for(new_mapping in new_mapping_names){
# things i've tried:
# mapping <- add_modify_aes(mapping, aes_string(!!sym(new_mapping) = paste(new_mapping)))
# mapping <- add_modify_aes(mapping, aes_string(eval(parse(text=new_mapping)) = paste(new_mapping)))
mapping <- add_modify_aes(mapping, aes_string(as.name(new_mapping) = new_mapping))
# mapping[[new_mapping]] <- quo(!!new_mapping)
}
mapping

在这个过程的最后,我希望映射看起来像:

> mapping
Aesthetic mapping: 
* `x`      -> `X`
* `y`      -> `Y`
* `colour` -> `COLOUR`
* `a` -> `a`
* `b` -> `b`
* `c` -> `c`
* `d` -> `d`

这样做的原因是,我可以将生成的ggplot对象(ggplt(传递给ggplotly,并使用映射中的任何内容作为工具提示:

df <- data.frame(X=rnorm(10),Y=rnorm(10),
COLOUR = sample(c('A', 'B', 'C'), 10, T),
a = 1:10, b=11:20, c=21:30, d=31:40)
ggplt <- ggplot(df, mapping) + geom_point()
ggplotly(ggplt, tooltip = new_mapping_names)

new_mapping_names不会总是字母[1:4]。如有任何帮助,我们将不胜感激。干杯

虽然我没有使用您指定的函数,但我想下面的解决方案可以解决您的问题

> df <- data.frame(X=rnorm(10),Y=rnorm(10),
+                  COLOUR = sample(c('A', 'B', 'C'), 10, T),
+                  a = 1:10, b=11:20, c=21:30, d=31:40)
> mapping <- aes(x=X, y=Y, col=COLOUR)
> df
X           Y COLOUR  a  b  c  d
1   0.6138723  1.61837122      B  1 11 21 31
2   0.5259420 -0.80905208      B  2 12 22 32
3  -0.4236438  1.41827060      C  3 13 23 33
4   0.9877539 -0.33813806      C  4 14 24 34
5   0.9751136  0.03876423      C  5 15 25 35
6   0.8123134 -1.23545463      A  6 16 26 36
7  -0.6657758  0.96099869      C  7 17 27 37
8  -1.2342100 -1.78106632      A  8 18 28 38
9  -0.4051921  1.22354846      A  9 19 29 39
10  0.5225744 -0.05270590      B 10 20 30 40
> mapping
* x      -> X
* y      -> Y
* colour -> COLOUR
> len<-length(mapping)
> new_mapping_names <- letters[1:3]
> new_mapping_names
[1] "a" "b" "c"
> for(i in 1:length(new_mapping_names)){
+   mapping[i+len][[1]]<-as.name(new_mapping_names[i])#adding desired number of aesthetics and their values
+   names(mapping)[i+len] <- new_mapping_names[i]#naming them
+ }
> mapping
* x      -> X
* y      -> Y
* colour -> COLOUR
* a      -> a
* b      -> b
* c      -> c

相关内容

  • 没有找到相关文章