Curlew
Curlew

Reputation: 1034

How to catch a ggplot object in a new function

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 like this

g <- ggplot() + ... # Additional stuff
g + myfunction(g, ...)

How can I make it so that it works like this (so the typical grammar of graphics structure):

ggplot() + ... + myfunction()

My new function addresses the geom layers in a passed ggplot object and I need to address them somehow. In particular I need the info in the gg$layers[[1]]$geom structure.

Any help appreciated and I hope that the question is clear.

Upvotes: 1

Views: 100

Answers (1)

baptiste
baptiste

Reputation: 77096

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")

enter image description here

Upvotes: 1

Related Questions