首页 文章

在R中,如何存储插图以便以后使用grid.arrange进行排列?

提问于
浏览
3

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

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

这正是我喜欢的方式(一个大图,在viewPort中指定的区域中绘制了自定义小图) .

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

grid.arrange(arrangeGrob(..))

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

非常感谢你!

EDIT: 在这里回应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)

这会生成我想要的图形,但是我无法使子图形成正确的大小('s supposed to be a small graph in the bottom left corner of the plot). This is probably really basic, but I haven' t之前使用 gtable ,只使用 grid/gridExtra .

非常感谢!

1 回答

  • 2

    您可以使用 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)
    

    enter image description here

相关问题