保存grid.arrange()图(具有不同的高度)

时间:2016-06-08 04:45:20

标签: r ggplot2 gridextra

使用dfyou can download it from here)和以下代码

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))

我得到了这个情节(我使用Rstudio导出它&gt;导出&gt;另存为图像)

enter image description here

我检查了several questions关于如何保存grid.arrange()图但没有一个与我的问题类似,其中顶部图是1/5,底部图是总高度的4/5最后的情节。

我尝试了以下代码

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

结果如下所示。正如预期的那样,每个情节g.topg.bottom代表最终情节高度的50%g

enter image description here

有关如何在最终情节中导出不同高度的grid.arrange()图的任何建议吗?

1 个答案:

答案 0 :(得分:4)

arrangeGrobgrid.arrange的双胞胎妹妹,不会画画。你可以给它相同的参数并ggsave它,

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

请注意,如果y轴不同,则两个图可能会有些不对齐。为了获得更好的结果,您可以使用gtable函数,例如通过实验egg包:

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