如何在新函数中捕获ggplot对象

时间:2015-09-05 10:37:09

标签: r ggplot2

我想extent一些带有附加功能的ggplot功能。该函数有效,但只有传递ggplot对象作为一个整体。

所以喜欢这个

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

我怎样才能使它像这样工作(所以图形结构的典型语法):

ggplot() + ... + myfunction()

我的新函数解决了传递的ggplot对象中的geom层,我需要以某种方式解决它们。特别是我需要gg$layers[[1]]$geom结构中的信息。

任何帮助表示赞赏,我希望问题清楚。

1 个答案:

答案 0 :(得分:1)

您可以在+.gg方法中添加内容,但这不是一个非常干净或健壮的过程

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