Saving plots using grid_draw method instead of gri

2019-05-11 04:53发布

I have used gridExtra to create 2 plots next to each other and I can save the object using ggsave

However, the plots are misaligned in gridExtra so I used this method

 #Method 2 - gtable
 require(gtable)
 #Extract Grobs
 g1<-ggplotGrob(left)
 g2<-ggplotGrob(right)
 #Bind the tables
  g<-gtable:::cbind_gtable(g1, g2, "first")
 #Remove a row between the plots
 g <- gtable_add_cols(g, unit(-1,"cm"), pos=ncol(g1))
 #draw
 grid.newpage()
 grid.draw(g)

this method is covered in this link

The perils of aligning plots in ggplot

It worked beautifully for my graphs but when I save the

object <- grid.draw(g)

the object is NULL when I try to look at it and I am not sure how to save it as a png

the gridExtra method can be saved as an object and saved using

ggsave('g.png',width=6,height=4,dpi=600)

how would you save grid.draw output? I tried saving it using Rstudio UI but it only saves one plot not both next to each other

3条回答
Evening l夕情丶
2楼-- · 2019-05-11 05:20

This should work.

png("g.png", plot=grod.draw(g), width = 1000, height = 600, units = "px")
dev.off()
查看更多
女痞
3楼-- · 2019-05-11 05:23
ggsave('g.png', plot = g, width=6,height=4,dpi=600)
查看更多
老娘就宠你
4楼-- · 2019-05-11 05:37

Forgot to mention that width and height of png ( ) will depend on the plot you have so play around with it.

This is how gtable object is saved:

depending on the plot, the dimensions of the png can be adjusted to properly fit the plot

png("g.png",width = 1000, height = 600, units = "px") 
grid.draw(g) 
dev.off()
查看更多
登录 后发表回答