I want to extent
some ggplot functionalities with an additional function. The function works, however only if the ggplot object as a whole is passed on.
So
you could potentially add stuff to the +.gg
method, but it's not a very clean or robust procedure
library(ggplot2)
`+.gg` <- function (e1, e2)
{
e2name <- deparse(substitute(e2))
if (is.theme(e1))
ggplot2:::add_theme(e1, e2, e2name)
else if (is.ggplot(e1))
if (is.stuff(e2)) add_mystuff(e1, e2, e2name) else
ggplot2:::add_ggplot(e1, e2, e2name)
}
my_stuff <- function(x){
structure(list(x=x), class="stuff")
}
is.stuff <- function(x) isTRUE(inherits(x, "stuff"))
add_mystuff <- function(e1,e2,e2name){
ptitle <- e1$labels$title
title <- gsub("{{title}}", ptitle, e2$x, fixed = TRUE)
grid.newpage()
vp <- viewport(width=0.8, height=0.8)
grid.rect(vp=vp,gp=gpar(fill="grey95",col=NA))
grid.grill(vp=vp,gp=gpar(col="white"))
grid.points(vp=vp, pch=3, gp=gpar(cex=0.2, col="red"))
grid.text(title)
}
qplot(1,1) + ggtitle("this ggplot") +
my_stuff("ignoring {{title}},\n I'm drawing this instead")