【问题标题】:In R, how can I store an inset graph for later arranging it with grid.arrange?在 R 中,我如何存储一个插图以便以后用 grid.arrange 对其进行排列?
【发布时间】:2015-10-23 14:40:16
【问题描述】:

我创建了一个图表,我通过这个命令在其中插入了另一个图表(两个 ggplot2 对象):

    vp=viewPort(...)
    print(ggplotobject1)
    print(ggplotobject2, vp=vp)

这完全符合我的要求(一个大图,在 viewPort 中指定的区域中绘制了一个自定义小图)。

问题是我需要稍后使用这个组合图再次通过以下方式将其与其他图排列:

grid.arrange(arrangeGrob(..))

有人知道如何将我的组合图存储为 grob 吗?

真的非常感谢!

编辑: 在这里回应 baptiste 是一个可重现的例子:

library(ggplot2)
library(gtable)
library(grid)

data<-mtcars
main_plot<-ggplot(data,aes(hp,mpg,group=cyl))+
  geom_smooth(method="lm")+geom_point()+
  facet_grid(.~gear)
sub_plot<-ggplot(data,aes(disp,wt,color))+geom_point()

gtable_main<-ggplot_gtable(ggplot_build(main_plot))
gtable_sub<-ggplot_gtable(ggplot_build(sub_plot))
gtable_show_layout(gtable_main)
gtable_main2<-gtable_add_grob(gtable_main,gtable_sub,t=4,l=4,b=1,r=1) 
grid.draw(gtable_main2)

这会生成我想要的图形,但我无法使子图的大小正确(它应该是图左下角的一个小图)。这可能是非常基本的,但我之前没有使用过gtable,并且只使用过一点点grid/gridExtra

非常感谢!

【问题讨论】:

    标签: r ggplot2 viewport gridextra


    【解决方案1】:

    您可以使用annotation_custom 或编辑gtable,而不是打印到不同的视口。

    gm <- ggplotGrob(main_plot)
    gs <- ggplotGrob(sub_plot)
    
    library(gtable)
    library(grid)
    panel.id <- 1
    panel <- gm$layout[gm$layout$name == "panel",][panel.id,]
    
    inset <- grobTree(gs, vp=viewport(width=unit(1,"in"), x=0.8, y=0.8,
                                      height=unit(1,"in")))
    gm <- gtable_add_grob(gm, inset, l=panel$l, t=panel$t)
    grid.newpage()
    grid.draw(gm)
    

    【讨论】:

    • 感谢您的回答。我曾尝试使用annotation_custom,但由于它是一个多面图,我会为每个方面重复它,这是我不想要的。关于gtable 编辑,您能否举个例子说明它是如何工作的?不幸的是,我还没有使用 gtables 的经验。再次感谢!
    • 听从您的建议,我一直在努力理解gtable。我几乎做到了我想要的,但我无法思考如何使“插入”图的大小正确(l,t,r,b 只是为了位置,对吧?)。你能给我一个提示吗?非常感谢!
    • 请提供一个最小的独立的可重现示例
    • 巴蒂斯特,非常感谢您!这就是我要找的。那么诀窍是在插图上使用grobTree 在主图中指定其视口,对吗?非常感谢 - 我会投赞成票,但我的声誉还不够高。
    • 是的。可能还有其他方法,但这似乎可以解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    相关资源
    最近更新 更多