【问题标题】:Saving grid.arrange() plot (with different heights)保存 grid.arrange() 绘图(具有不同的高度)
【发布时间】:2016-10-08 04:30:23
【问题描述】:

使用df (you 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 > export > Save as Image 导出它)

我检查了 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.top 和 g.bottom 的每个图都代表最终图 g 高度的 50%

有什么建议如何在最终图中导出具有不同高度的grid.arrange() 图?

【问题讨论】:

  • @baptiste 非常感谢您的时间和帮助。它对我很好。您能否将其添加为答案?

标签: r ggplot2 gridextra


【解决方案1】:

arrangeGrob 是不会画画的grid.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))

【讨论】:

    猜你喜欢
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    相关资源
    最近更新 更多