S3 方法:扩展 ggplot2 `+.gg` 函数

问题描述

我正在尝试使用一个新类扩展 ggplot2,我们将在此示例中将其称为 foo。目标是编写一个 +.foo 方法来代替 +.gg。但是我遇到了“不兼容的方法”的问题

设置

目前我可以编写 ggplot_add.foo_layer 这将使 plot 进入我的 foo 类,然后正常添加相应的层。

这个想法是,一旦 plot 对象继承了 foo,它就会在添加下一层时分派到 +.foo

我想这样做的原因是因为我想检查 foo 对象的结构是否仍然有效/与传入层兼容。这将使我不必为 ggplot_build 编写方法。

代码定义

library(ggplot2)

`+.foo` <- function(e1,e2){
  cat("Using foo ggplot +") # for Debugging
  NextMethod() #ideally just dispatches to `+.gg`
}

ggplot_add.foo_layer <- function(object,plot,object_name) {
  plot <- as_foo(plot)
  ggplot2:::add_ggplot(plot,object$layer,object_name) 
}

as_foo <- function(x){
  if(!is_foo(x)){
    class(x) <- c("foo",class(x))
  }
  x
}

is_foo <- function(x) inherits(x,"foo")

foo_layer <- function(x) structure(list(layer = x),class = "foo_layer")

错误

p1 <- ggplot(iris,aes(Sepal.Width,Sepal.Length,color = Species)) +
  geom_point()
class(p1)
#[1] "gg"     "ggplot"
p1 + geom_density(aes(y = after_stat(density)))


p2 <- ggplot(iris,color = Species)) +
  foo_layer(geom_point()) 

class(p2)
#[1] "foo"    "gg"     "ggplot"
p2 + geom_density(aes(y = after_stat(density)))
#Error in p2 + geom_density(aes(y = after_stat(density))) : 
#  non-numeric argument to binary operator
#In addition: Warning message:
#Incompatible methods ("+.foo","+.gg") for "+" 

从上面的代码 p1 + geom_* 执行得很好。但是,由于上述关于不兼容方法的错误,无法制作 p2 + geom_*。根据我对 S3 方法调度的了解,我不明白为什么这行不通。有人可以解释为什么会这样或我可以如何解决这个问题。

理想情况下,我不必编写方法 ggplot_build.foo,因为我希望使用其他包的 ggplot_build(如果它们存在)(例如 gganimate)。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)