R ggplot修改映射aes

4
我试图动态更新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://dev59.com/oWEi5IYBdhLWcg3wCYGY
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]。非常感谢您的帮助。 谢谢。

1个回答

2

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

> 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

太好了。完美地完成了工作。我想我需要更新一些软件包;我使用的 aes_string 版本将公式返回为列表元素,而不是符号。非常感谢! - Mark

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接