Saving plots using grid_draw method instead of gridExtra
Asked Answered
B

3

3

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

Barbital answered 14/10, 2015 at 19:40 Comment(0)
B
4

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()
Barbital answered 15/10, 2015 at 2:57 Comment(0)
M
0

This should work.

png("g.png", plot=grod.draw(g), width = 1000, height = 600, units = "px")
dev.off()
Mong answered 30/1, 2019 at 16:24 Comment(0)
A
0
ggsave('g.png', plot = g, width=6,height=4,dpi=600)
Aldas answered 1/2, 2019 at 20:48 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.