代码之家  ›  专栏  ›  技术社区  ›  stackinator Brenton Wiernik

ggsave()用于ggplot中网格排列的选项

  •  0
  • stackinator Brenton Wiernik  · 技术社区  · 7 年前

    ggsave() 似乎不适用于网格包(见下文)。如何保存此组合图 p1 情节 p2 . 以下代码只保存最后一个绘图 P2 ggplot()看到。

    library(tidyverse)
    p1 <- ggplot(mpg, aes(fl)) + geom_bar()
    p2 <- ggplot(mpg, aes(cty, hwy)) + geom_col()
    grid.newpage()
    grid.draw(rbind(ggplotGrob(p1), ggplotGrob(p2), size = "last"))
    ggsave("mpg.png")
    
    3 回复  |  直到 7 年前
        1
  •  1
  •   Parfait    7 年前

    考虑使用 gridExtra->code>。如本文中所述,vignette vignette , gridextra ,building off of gtable(a higher-level layout scheme),provides more facility in arrangement multiple grobs on a page,while grid provides low le用于创建图形对象(grobs)的vel函数。

    库(ggplot2)
    库(GridExtra)
    
    p1<-ggplot(mpg,aes(fl))+geom_bar()。
    p2<-ggplot(mpg,aes(cty,hwy))+geom_col())
    
    P<-网格。排列(p1,p2)
    
    ggsave(plot=p,filename=“myplot.png”)。
    < /代码> 
    
    

    ,格里德斯特拉,以…为基础gtable(更高级的布局方案),在一个页面上安排多个grob时提供了更多的便利,而grid包提供了创建图形对象(grobs)的低级功能。

    library(ggplot2)
    library(gridExtra)
    
    p1 <- ggplot(mpg, aes(fl)) + geom_bar()
    p2 <- ggplot(mpg, aes(cty, hwy)) + geom_col()
    
    p <- grid.arrange(p1, p2)
    
    ggsave(plot=p, filename="myPlot.png")
    

    Plot Output

        2
  •  0
  •   M. Fraz Ismail    7 年前

    我想你可以做这样的事。

    #plotFile
    g1=file.path(HomeDir,plotFile)
    f1=grid.arrange(p1,p2, ncol=2, top=textGrob("Multiple Plots", gp=gpar(fontsize=12, font = 2))) #arranges plots within grid
    g <- arrangeGrob(f1) #generates g
    #save
    ggsave(g1, g,width = 29.7, height = 21, units = 'cm') #saves g
    
        3
  •  0
  •   Community Mohan Dere    7 年前

    您必须先分配新的组合,然后使用ggsave()打印它。

    # here I name it to_print    
      to_print <- rbind(ggplotGrob(p1), ggplotGrob(p2), size = "last")
    
    
    ggsave(filename = "mpg.png", plot = to_print)
    

    希望这有帮助!