How to access the data frame that was passed to ggplot ()?

I want to set the line N=xxxas the title of my figure, where xxxis the number of observations in the data frame that I pass as an argument datato ggplot(). In my current code, I explicitly pass this data frame a second time as an argument sprintf(), which I use internally labs():

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

This creates the desired header, but it will not work with more complex tasks: I use the channel dplyrto build the data frame that is being created, and since it is a laborious process, I wouldn’t want to repeat the pipe a second time to get the number of rows, as in the example .

So, how do I access the data frame that was passed as an argument ggplot()from the argument specification of the functions that are used to change the graph?

+4
source share
2 answers
mtcars %>% {
  ggplot(., aes(mpg, hp)) + 
  labs(title = paste("N =", nrow(.))) + 
  geom_point()
}

Note that when ending the entire ggplotcall in {...}braces, you must use the .dot pronoun for the data argument in ggplot(., ...). You can then call this object back using a pronoun .anywhere in the call.

enter image description here

+7
source

Another option that uses another function magrittrfor pipe lining: the tee operator %T>%.

library(ggplot2)
library(magrittr)
# to solidify where the variable will be out-of-scope defined
nr <- "oops"
mtcars %T>%
  { nr <<- nrow(.) } %>%
  ggplot(aes(mpg, hp)) + 
    labs(title=sprintf("N=%i", nr)) + 
  geom_point()

(This can also be done using dplyr do({nr <<- nrow(.)}) %>%.)

:

  • " ", ggplot . ( , .)

  • , nr ggplot. nr, , , .

+3

Source: https://habr.com/ru/post/1681386/


All Articles