防止grid.arrange用autoplot压缩grobs

时间:2017-06-15 21:29:11

标签: r ggplot2 grob

我使用grid.arrange()绘制带有一列的4个折线图。如果尺寸很大,将文件保存为.png或.pdf时,grobs看起来没问题。但是,当我缩小绘图的高度时,顶部grob会被压缩。

如何防止grid.arrange压缩grobs?

一些丑陋的代码:

(a<-autoplot(mars.prcp1yrs) + labs(y="", x="") +theme_light()+ylim(60,210)+
   theme(text=element_text(size=8),
         axis.text.y=element_text(size=8),axis.text.x=element_blank(),
         axis.title.y=element_blank(),
         axis.ticks.x=element_blank(), 
         plot.margin=unit(c(0.1,0.1,0.1,0.1),"in")))

(b<-autoplot(jupiter.prcp1yrs) + labs(y="",x="")+ theme_light()+ylim(60,210)+
  theme(text=element_text(size=8),axis.text.y=element_text(size=8),
        axis.text.x=element_blank(),axis.title.y=element_blank(),
        axis.ticks.x=element_blank(),plot.margin=unit(c(-0.3,0.1,0.1,0.1),"in")))

(c<-autoplot(saturn.prcp1yrs) +labs(y="",x="") + theme_light()+ylim(60,210)+
  theme(text=element_text(size=8),
        axis.text=element_text(size=8),
        axis.text.x=element_blank(),axis.title.y=element_blank(),
        axis.ticks.x=element_blank(),plot.margin=unit(c(-0.3,0.1,0.1,0.1),"in")))

(d<-autoplot(earth.prcp1yrs) +labs(y="",x="") +theme_light()+ylim(60,210)+
  theme(text=element_text(size=8),axis.text=element_text(size=8),
        axis.ticks.x=element_blank(),axis.title.y=element_blank(),
        plot.margin=unit(c(-0.3,0.1,0.1,0.1),"in")))


prcp.grid<-grid.arrange(a,b,c,d, ncol=1)


png("plot.png",width=3740,height=1000,res=500)
old.par <- par(mfrow=c(2, 2))
grid.arrange(prcp.grid, ncol=2)
par(old.par)
dev.off()

这是输出 (我使用这个纵横比来戏剧化顶部凹凸的压缩。): enter image description here

1 个答案:

答案 0 :(得分:0)

我发现最好使用fortify()将zoo对象转换为数据框。

因此,按照上面的例子,我首先将每个zoo对象转换为数据框:

mars.prcp.1yr<-fortify(mars.prcp1yrs)
jupiter.prcp.1yr<-fortify(jupiter.prcp1yrs)
saturn.prcp.1yr<-fortify(saturn.prcp1yrs)
earth.prcp.1yr<-fortify(earth.prcp1yrs)

然后我在每个数据框中添加了一个公共变量(行星):

#add planet as variable
mars.prcp.1yr$planet <- "Mars"
jupiter.prcp.1yr$planet <- "Jupiter"
saturn.prcp.1yr$planet <- "Saturn"
earth.prcp.1yr$planet <- "Earth"

更改zoo对象名称以更好地表示变量:

    #change to common colnames
    mars.prcp.1yr <- rename(mars.prcp.1yr, Precipitation = mars.prcp1yrs)
    jupiter.prcp.1yr <- rename(jupiter.prcp.1yr, Precipitation = jupiter.prcp1yrs)
    saturn.prcp.1yr <- rename(saturn.prcp.1yr, Precipitation = saturn.prcp1yrs)
    earth.prcp.1yr <- rename(earth.prcp.1yr, Precipitation = earth.prcp1yrs)

然后,行将所有数据帧绑定到单个数据帧中:

  prcp.1yr <- bind_rows(mars.prcp.1yr,jupiter.prcp.1yr,saturn.prcp.1yr,earth.prcp.1yr) 

然后在标准facet_grid(planet~.)调用中使用ggplot()参数。