How to reference to the data within a ggplot2 call

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.

myfun <- function(data, x){

  if(nrow(data) > x){
ggplot(mtcars, aes(cyl, disp)) + geom_point() + myfun(mtcars, 5)

So instead I would put

ggplot(mtcars, aes(cyl, disp)) + geom_point() + myfun(5)

This isn't quite the thing you asked for but maybe it will give you something to work with

myfun <- function(plot, x){
  data <- layer_data(plot) 
   if(nrow(data) > x){
     return(plot + theme_light())
     return(plot + theme_dark())

{ggplot(mtcars, aes(cyl, disp)) + geom_point()} %>% myfun(90)

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.

  1. 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)
  1. 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)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.