I'm trying to make ggplot2 to take lists and make elements of the lists available to other custom geom functions.
I have a new ggplot function that accepts lists:
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
}
I create my list, and I plot the first 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))
Ideally I would like to create something like this (which doesn't work), another geom that by default takes the data_ext
from the ggplot object
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))
I see that that my second data.frame is inside the ggplot object, but I don't know how to access it; that is, ggplot(l)$data_ext
works.
I've tried playing with ggproto but I'm not proficient enough to understand what to do with it, and if it could help.
ADDED By the way, I can achieve what I want with the pipe, but I don't want to confuse potiential users of my functions:
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))