我正在尝试动态更新ggplot对象的映射,但无法弄清楚该怎么做。
似乎有another post of 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]。任何帮助将不胜感激。 干杯
答案 0 :(得分:1)
尽管我没有使用您指定的功能,但是我想以下解决方案可以解决您的问题
payment_detail_id