我正在尝试延长ggplot2
一个新的类,我们称之为foo
对于这个例子。目标是写一个+.foo
将用来代替的方法+.gg
。但是我遇到了“方法不兼容”的问题
设置
目前我可以写ggplot_add.foo_layer
这将使plot
进入我的foo
class 然后照常添加相应的层。
这个想法是,一旦绘图对象继承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, aes(Sepal.Width, Sepal.Length, 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
).