Change geom default aesthetics as part of theme component only – ggplot2

  • A+
Category:Languages

For a custom ggplot2 theme I'd like to change the default aesthetic of some geom, say I want red dots instead of black dots.

From this answer I know we can change defaults for a geom using the function update_geom_default but I wonder if it is possible to change the colour only when we call theme_red_dots?

Example of my naive attempt:

library(ggplot2)  theme_red_dots <- function(...) {   update_geom_defaults("point", list(colour = "red"))   theme_minimal() +     theme(...) } 

Looks good here:

ggplot(mtcars, aes(mpg, disp)) +    geom_point() +    theme_red_dots() 

Change geom default aesthetics as part of theme component only - ggplot2

But I'd like the points to be black again when I call

ggplot(mtcars, aes(mpg, disp)) +    geom_point() 

Change geom default aesthetics as part of theme component only - ggplot2

Thanks in advance!


Below is an example of why I thought this could be useful. We can change panel.background to be black fairly easy but this would make it impossible to see the points if we don't map an aesthetic to colour. (The usefulness of this theme_black can certainly be discussed, but I would like to avoid an argument about that.)

theme_black <- function(...) {   theme_minimal() +     theme(panel.background = element_rect(fill = "black")) +     theme(...) }  # update_geom_defaults("point", list(colour = "black")) ggplot(mtcars, aes(mpg, disp)) +    geom_point() +    theme_black() 

Change geom default aesthetics as part of theme component only - ggplot2

Changing the colour of the points inside geom_point() is an option here (see @zx8754 answer), but this requires the user of theme_black() to change it, while I am wondering if there is a way to do this right inside theme_*.

 


Instead of changing defaults, make custom geom_point:

library(ggplot2)  # make custom geom with red as default geom_point_red <- function()geom_point(col = "red")  ggplot(mtcars, aes(mpg, disp)) +    geom_point_red() 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: