I want to inherit the data from within a ggplot call and not have to reference it again. So for example in my code below, I reference to mtcars twice, but I want it to "inherit" the data within my function.
This is the kind of thing that would be much easier to do if ggplot2 objects were combined using pipes (%>%) rather than by addition (+). I'm curious to see if anyone has an easy way of doing this, but this has the feel of a task (as stated) that is not worth the effort, unless this is a very small reprex of bigger programming task.
I would avoid trying to insert conditional logic like this in a ggplot "chain" via the + operator by trying one of these two ideas.
Wrap the entire ggplot creation in a function
dark_light_plot <- function(data, x, ...) {
g <- ggplot(data, aes(...)) + geom_point()
g + if (nrow(data) > x) theme_light() else theme_dark()
}
dark_light_plot(mtcars, 5, cyl, disp)
Write a function that adds the theme to an existing ggplot.
add_dark_light_theme <- function(g, x) {
g + if (nrow(layer_data(g)) > x) theme_light() else theme_dark()
}
g <- ggplot(mtcars, aes(cyl, disp)) + geom_point()
add_dark_light_theme(g, 5)