如何覆盖R中的ggplot函数?

时间:2015-07-17 00:22:31

标签: r ggplot2

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

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

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

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

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

2 个答案:

答案 0 :(得分:10)

使用::运算符指定要调用ggplot2包中的函数版本,而不是您刚刚在全局工作区中创建的版本。即

之类的东西
ggplot <- function(...) {
  ggplot2::ggplot(...) + theme_bw()
}

应该有用(虽然我还没有测试过它!)

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

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

这可以说比你的解决方案更容易,更惯用/更透明。

答案 1 :(得分:0)

另一种解决方案是修改Rprofile.site文档中的启动代码。 (对于Windows:它位于C:\ Program Files \ R \ R-n.n.n \ etc)。

将此代码添加到其中:

.First <- function(){
ggplot2::theme_set(theme_bw())
}

.First中的任何内容都将在启动时运行。

相关问题