如何覆盖R中的ggplot函数?

Jes*_*ica 4 r ggplot2

theme_bw在几乎所有的R图中都使用了该命令,因此我想要覆盖ggplot函数,如下所示:

# Override the ggplot function to use theme_bw by default
ggplot <- function(...) {
  ggplot(...) + theme_bw()
}
Run Code Online (Sandbox Code Playgroud)

然而,当我这样做时,翻译抱怨说

Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
Run Code Online (Sandbox Code Playgroud)

有没有办法指定函数中的ggplot应该是ggplot的原始版本,而不是我刚写的那个?

Ben*_*ker 10

使用::运算符指定要调用ggplot2包中存在的函数的版本,而不是您刚刚在全局工作空间中创建的版本.即类似的东西

ggplot <- function(...) {
  ggplot2::ggplot(...) + theme_bw()
}
Run Code Online (Sandbox Code Playgroud)

应该工作(虽然我还没有测试过!)

我也非常喜欢theme_bw().我这样做的方法是theme_set()在加载包装后立即使用,例如

library("ggplot2"); theme_set(theme_bw())
Run Code Online (Sandbox Code Playgroud)

这可以说比你的解决方案更简单,更惯用/透明.