Nip
Nip

Reputation: 470

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?

Upvotes: 1

Views: 204

Answers (1)

Paul
Paul

Reputation: 9107

withr::with_package temporarily loads a package.

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

Upvotes: 1

Related Questions