I'm trying to dynamically update the mapping of a ggplot object, but can't figure out how to go about it.
There was another post of stackoverflow that seems to address most of the issue, but I don't know how to name the aes mapping dyanmically...
# start of mapping:
mapping <- aes(x = X, y = Y, col = COLOUR)
This gives:
> mapping
Aesthetic mapping:
* `x` -> `X`
* `y` -> `Y`
* `colour` -> `COLOUR`
I then want to add in a bunch more mappings to the aes function.
# 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
At the end of the process, I want mapping to look like:
> mapping
Aesthetic mapping:
* `x` -> `X`
* `y` -> `Y`
* `colour` -> `COLOUR`
* `a` -> `a`
* `b` -> `b`
* `c` -> `c`
* `d` -> `d`
The reason for doing this is so that I can pass the resulting ggplot object (ggplt) to ggplotly and use whatever is in the mapping as a tooltip:
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 wont always be the letters[1:4]. Any help would be greatly appreciated. Cheers