我正在尝试使 ggplot2 获取列表并使列表中的元素可用于其他自定义几何函数。
我有一个接受列表的新 ggplot 函数:
ggplot.list <- function(data = NULL,
mapping = ggplot2::aes(),
...,
environment = parent.frame()) {
p <- ggplot2::ggplot(data=data[[1]],mapping=mapping,..., environment=environment)
p$data_ext <- data[[2]]
p
}
我创建了我的列表,并绘制了第一个 data.frame:
l <- list(tibble(x=1:10, y=1:10), tibble(x=1:10+100, y =1:10+200))
ggplot(l) + geom_point(aes(x=x,y=y))
理想情况下,我想创建这样的东西(这不起作用),另一个默认情况下data_ext
从 ggplot 对象中获取的 geom
geom_point2 <- function (mapping = NULL, data_ext = NULL, stat = "identity", position = "identity",
..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE)
{
layer(data_ext = data_ext, mapping = mapping, stat = stat, geom = GeomPoint,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...))
}
ggplot(l) + geom_point(aes(x=x,y=y)) + geom_point2(aes(x=x,y=y))
我看到我的第二个 data.frame 在 ggplot 对象内,但我不知道如何访问它;也就是说,ggplot(l)$data_ext
有效。我试过玩 ggproto,但我不够熟练,无法理解如何处理它,以及它是否有帮助。
添加 顺便说一句,我可以用管道实现我想要的,但我不想混淆我的功能的潜在用户:
pipe_point2 <-function (plot, mapping = NULL, data = NULL, stat = "identity", position = "identity",
..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE)
{
plot + layer(data = plot$data_ext, mapping = mapping, stat = stat, geom = GeomPoint,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...))
}
{ggplot(l) + geom_point(aes(x=x,y=y))} %>% pipe_point2(aes(x=x,y=y))