Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add grid.text to arrange.grob for export as PNG

I am attempting to create and export, as a PNG file, with several plots arranged in a 3 X 2 matrix. Each row (containing two plots) has its own X axis. I can add the additional axes via a grid.text but this grid.text is not exported with the PNG file. How does one add additional text or Grobs to the plot matrix for PNG export?

Below is a sample 2 X 2 plot matrix

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"))
like image 736
tcacek Avatar asked Jun 23 '15 21:06

tcacek


1 Answers

You need to print grid objects. (It's a FAQ):

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

like image 143
IRTFM Avatar answered Sep 20 '22 21:09

IRTFM