我正在尝试动态更新 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]。任何帮助将不胜感激。干杯