shiny
shiny

Reputation: 3502

Saving grid.arrange() plot (with different heights)

Using df (you can download it from here), and the code below

library(ggplot2)
library(gridExtra)

df <- read.csv("df_rain_flow.csv") 
df$Date <- as.Date(df$Date, format="%Y-%m-%d") 

g.top <- ggplot(df, aes(x = Date, y = Rain, ymin=0, ymax=Rain)) +
  geom_linerange(size = 0.2, color = "#3399FF", alpha =0.3) +
  scale_y_continuous(limits=c(170,0), expand=c(0,0), trans="reverse")+
  theme_classic()+
  labs(y = "Rain (mm)")+
  theme(plot.margin = unit(c(5,5,-32,6),units="points"),
        axis.title.y= element_text(color="black", size = 10, vjust = 0.3),
        axis.text.y=element_text(size = 8))

g.bottom <- ggplot(df, aes(x = Date, y = Flow)) +
  geom_line(size = 0.06, color = "blue") +
  scale_x_date(breaks = seq(as.Date("1993-01-01"), 
                            as.Date("2016-12-01"), by="1 year"), 
               labels = date_format("%Y"))+
  theme_classic()+
  labs(x = "", 
       y = expression(Flow~~(m^{3}~s^{-1})))+
  theme(plot.margin = unit(c(0,5,1,1),units="points"),  
        axis.title.x = element_text(color="black", face="bold", size = 10, margin=margin(10,0,0,0)),
        axis.title.y= element_text(color="black", face="bold", size = 12 ),
        strip.text = element_text(color="black", size= 8, face="bold"),
        axis.text.x=element_text(angle=35,vjust=1, hjust=1,size = 8),
        axis.text.y=element_text(size = 8, face="bold"))

grid.arrange(g.top,g.bottom, heights = c(1/5, 4/5))

I got this plot (I exported it using Rstudio > export > Save as Image)

enter image description here

I checked several questions about how to save grid.arrange() plot but none of them is similar to my question where the top plot is 1/5 and the bottom plot is 4/5 of total height of the final plot.

I tried the code below

g <- arrangeGrob(g.top, g.bottom)
ggsave("plot.png", g, height = 5.2, width = 9.6, dpi = 600)

The result is shown below. As expected each plot g.top and g.bottom represents 50% of the height of the final plot g

enter image description here

Any suggestions how to export the grid.arrange() plots with different heights in the final plot?

Upvotes: 0

Views: 5314

Answers (1)

baptiste
baptiste

Reputation: 77106

arrangeGrob is the twin sister of grid.arrange that doesn't draw. You can give it the same arguments and ggsave it,

g <- arrangeGrob(g.top, g.bottom, heights = c(1/5, 4/5))
ggsave("plot.png", g, height = 5.2, width = 9.6, dpi = 600)

Note that the two plots may be somewhat misaligned, if the y axes are different. For better results, you could use gtable functions, e.g. via the experimental egg package:

#devtools::install_github("baptiste/egg")
library(egg)
library(grid)
ggarrange(g.top, g.bottom, heights = c(1/5, 4/5))

Upvotes: 3

Related Questions