如何在新函数中捕获ggplot对象 [英] How to catch a ggplot object in a new function
问题描述
我想要范围
一些附加功能的ggplot功能。这个函数可以工作,但是只有当ggplot对象作为一个整体被传递时。
所以,像这样
g < - ggplot()+ ...#附加东西
g + myfunction(g,...)
我怎样才能使它像这样工作(所以典型的图形结构语法):
<$ pre $
$ b $ g $我的新函数解决了通过ggplot对象中的几何图层,我需要以某种方式解决它们。特别是我需要 gg $ layers [[1]] $ geom
结构中的信息。
我希望这个问题很明确。
gg 方法,但它不是一个很干净或强大的过程。
pre $ library $ g $ (e1,e2)
{
e2name< - deparse(替代(e2))
if(is.theme(e1,e2) ))
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,stuff))
$(b) b $ b 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(ignore {{ title}},\\\
我正在画这个)
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.
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")
这篇关于如何在新函数中捕获ggplot对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!