Search code examples
rggplot2magrittr

How do I access the data frame that has been passed to ggplot()?


I want to set the string N=xxx as the title of my figure, where xxx is the number of observations in the data frame that I pass as the data argument to ggplot(). In my current code, I explicitly pass that data frame a second time as an argument to sprintf() which I use inside of labs():

ggplot(mtcars, aes(mpg, hp)) + 
    labs(title=sprintf("N=%i", nrow(mtcars))) + 
    geom_point()

This does produce the desired title, but it won't work with more complex tasks: I use a dplyr pipe to construct the data frame that is being plotted, and as this is a time-consuming process, I wouldn't want to repeat the pipe a second time to obtain the number of rows like in the example.

So, how do I access the data frame that has been passed as an argument to ggplot() from within the argument specifications of the functions that are used to modify the plot?


Solution

  • mtcars %>% {
      ggplot(., aes(mpg, hp)) + 
      labs(title = paste("N =", nrow(.))) + 
      geom_point()
    }
    

    Note that when wrapping the whole ggplot call in {...} curly braces, you must use the . dot pronoun for the data argument in ggplot(., ...). Then you can call back that object using the . pronoun anywhere in the call.

    enter image description here