Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override the ggplot function in R?

Tags:

r

ggplot2

I use the theme_bw command in pretty much all of my R plots, so I was thinking of overriding the ggplot function like so:

# Override the ggplot function to use theme_bw by default
ggplot <- function(...) {
  ggplot(...) + theme_bw()
}

However, when I do this, the interpreter complains, saying

Error: evaluation nested too deeply: infinite recursion / options(expressions=)?

Is there any way to specify that the ggplot inside the function should be the original version of ggplot, not the one I just wrote?

like image 342
Jessica Avatar asked Dec 19 '22 02:12

Jessica


1 Answers

Use the :: operator to specify that you want to call the version of the function that lives in the ggplot2 package, not the version you just created in the global workspace. i.e. something like

ggplot <- function(...) {
  ggplot2::ggplot(...) + theme_bw()
}

should work (although I haven't tested it!)

I also have a strong preference for theme_bw(). The way I do it is to use theme_set() right after I load the package, e.g.

library("ggplot2"); theme_set(theme_bw())

which arguably is just as easy and more idiomatic/transparent than your solution.

like image 142
Ben Bolker Avatar answered Jan 11 '23 17:01

Ben Bolker