Change geom default aesthetics as part of theme component only

Another solution is to detach and reattach ggplot2 (apparently you can do this within custom ggplot2 theme function).

library(ggplot2)

theme_red_dots <- function(...) {
    # wanted theme
    update_geom_defaults("point", list(colour = "red"))

    # Plot
    p <- theme_minimal() + 
        theme(...)

    # Detach and reattach ggplot2
    detach("package:ggplot2", unload = TRUE); library(ggplot2)

    # Return wanted plot
    return(p)
}
# red dots
ggplot(mtcars, aes(mpg, disp)) + 
    geom_point() + 
    theme_red_dots()
# black (default) dots
ggplot(mtcars, aes(mpg, disp)) + 
    geom_point()

Works with wanted theme_black too:

theme_black <- function(...) {
    update_geom_defaults("point", list(colour = "red"))
    p <- theme_minimal() +
        theme(panel.background = element_rect(fill = "black")) +
        theme(...)
    detach("package:ggplot2", unload = TRUE); library(ggplot2)
    return(p)
}

# Plots with black background
ggplot(mtcars, aes(mpg, disp)) + 
    geom_point() + 
    theme_black()

# Plots with default background
ggplot(mtcars, aes(mpg, disp)) + 
    geom_point()

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()

The released version of ggplot2 doesn't currently offer a way to do this. However, this is a fairly old feature request and has been under development since the summer of 2018.

Tags:

R

Themes

Ggplot2