I\'m trying to set the default color for all geoms in a ggplot to something other than black. Note this is not about setting scale_color...
Simple example:<
In order to replace a geom default aesthetic with another one (for all geoms using that aesthetic), you can try the following code.
First define a function for getting default aes settings of all geoms from ggplot2
library(ggplot2)
library(purrr)
geom_aes_defaults <- function() {
geom_names <- apropos("^Geom", ignore.case = FALSE)
geoms <- mget(geom_names, env = asNamespace("ggplot2"))
map(geoms, ~ .$default_aes)
}
With geom_aes_defaults() you obtain a long list of all geom aesthetic mappings
$Geom
Aesthetic mapping:
$GeomAbline
Aesthetic mapping:
* `colour` -> "black"
* `size` -> 0.5
* `linetype` -> 1
* `alpha` -> NA
$GeomAnnotationMap
Aesthetic mapping:
* `colour` -> "NA"
* `fill` -> "grey20"
* `size` -> 0.5
* `linetype` -> 1
* `alpha` -> NA
$GeomArea
Aesthetic mapping:
* `colour` -> NA
* `fill` -> "grey20"
* `size` -> 0.5
* `linetype` -> 1
* `alpha` -> NA
...
The following function iterates over all geoms matching a given aesthetic and substitutes the corresponding values
replace_geom_aes_defaults <- function(name, old_aes, new_aes) {
matching_geoms <-
map(geom_aes_defaults(), name) %>%
compact() %>%
keep(~ !is.na(.) & . == old_aes)
geoms <- gsub("^Geom(.*)", "\\1", names(matching_geoms))
walk(geoms, update_geom_defaults, setNames(list(new_aes), name))
}
Now you can replace colors systematically, e.g. turn black into red by
replace_geom_aes_defaults("colour", "black", "red")
or even replace fill colors (for bar plots) by
replace_geom_aes_defaults("fill", "grey35", "red")