简体   繁体   中英

How to use `ggplot2`'s functions without loading the package?

When using ggplot2 , sometimes we need to use multiple functions in order to plot data:

library("ggplot2")
p <- ggplot(mpg) + 
  geom_bar(aes(x = .data$drv)) + 
  coord_flip()

An alternative way to do this plot without loading the whole ggplot2 package would be:

p <-ggplot2::ggplot(ggplot2::mpg) + 
   ggplot2::geom_bar(ggplot2::aes(x = .data$drv)) + 
   ggplot2::coord_flip()

How can we do this plot without having to load the package throught library("ggplot2") , or having to write ggplot2:: for every function?

withr::with_package temporarily loads a package.

p <- withr::with_package("ggplot2", {
  ggplot(mpg) + 
    geom_bar(aes(x = drv)) + 
    coord_flip()
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM