添加grid.text到arrange.grob以导出为PNG

时间:2015-06-23 21:03:23

标签: r ggplot2 annotate grob

我正在尝试创建和导出作为PNG文件的几个以3 X 2矩阵排列的图。每行(包含两个图)都有自己的X轴。我可以通过grid.text添加其他轴,但是这个grid.text不会与PNG文件一起导出。如何将其他文本或Grob添加到PNG导出的绘图矩阵中?

以下是样本2 X 2绘图矩阵

a<-rnorm(100,56,3)
b<-rnorm(100,43,6)
c<-data.frame(cbind(a,b))
colnames(c) <- c("A","B")

library(ggplot2)
library(gridExtra)
library(grid)

plot1<-ggplot(c, aes(x=A, y=B))+  geom_point(size=3)+stat_smooth()+
ggtitle("Plot1")+ ylab("Y Axis")
plot1

plot2<-ggplot(c, aes(x=B, y=A))+   geom_point(size=3)+   stat_smooth()+
ggtitle("Plot2")+ ylab("Y Axis")
plot2

plot3<-ggplot(c, aes(x=B, y=A))+ geom_point(size=3)+stat_smooth(se=FALSE)+
ggtitle("Plot3")+ ylab("Y Axis")
plot3

plot4<-ggplot(c, aes(x=A, y=B))+ geom_point(size=3)+ stat_smooth(se=FALSE)+
ggtitle("Plot4")+ ylab("Y Axis")
plot4

grid.arrange(arrangeGrob(plot1,plot2,plot3, plot4,ncol=2,
                         sub=textGrob("A (hr)", vjust=0,gp = gpar(fontsize=20,   fontfamily="Times New Roman")),
                         left=textGrob("                 B (MPH)", rot=90,gp =      gpar(fontsize=18, fontfamily="Times New Roman"), vjust=1)))

grid.text("This is were the additional x-axis goes", x = unit(0.5, "npc"), y = unit(.51, "npc"),gp = gpar(fontsize=20, fontfamily="Times New Roman"))

1 个答案:

答案 0 :(得分:2)

您需要print网格对象。 (这是常见问题):

library(gridExtra)
png(); print( 
    grid.arrange(arrangeGrob(plot1,plot2,plot3, plot4,ncol=2,
                     sub=textGrob("A (hr)", vjust=0,gp = gpar(fontsize=20,   fontfamily="Times New Roman")),
                     left=textGrob("                 B (MPH)", rot=90,gp =      gpar(fontsize=18, fontfamily="Times New Roman"), vjust=1)))
             )

grid.text("This is were the additional x-axis goes", x = unit(0.5, "npc"), 
          y = unit(.51, "npc"),gp = gpar(fontsize=20, fontfamily="Times New Roman"))
 dev.off()

enter image description here