2015-09-05 22 views
1

我想extent某些ggplot功能附加功能。該函數可以工作,但是隻有在ggplot對象作爲整體被傳遞時才起作用。如何捕捉新功能中的ggplot對象

所以像這樣

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

我怎樣才能讓這個它是這樣工作的(這樣的圖形結構的典型語法):

ggplot() + ... + myfunction() 

我的新功能解決了GEOM層一個通過ggplot對象,我需要以某種方式解決它們。特別是我需要gg$layers[[1]]$geom結構中的信息。

任何幫助表示讚賞,我希望問題是明確的。

+1

看看'GGPLOT2 ::: 「+ GG」' – baptiste

+0

謝謝。添加元素的作品,但問題是我想從傳遞的'ggplot'對象查詢一些參數。目前正在嘗試'結構(list(...),class =「ggplot」)'' – Curlew

回答

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