Home > OS >  How to avoid automatic adjustment of the size of the plot when using facet_wrap?
How to avoid automatic adjustment of the size of the plot when using facet_wrap?

Time:12-11

Here is an example to illustrate what I want to do :

 simul<-data.frame(ID=rep(1:20,5),
                   TIME=rep(1:5,each=20),
                   VAR1=runif(100,0,10))
 fig1<-ggplot(data=simul[which(simul$ID <=15),],
           aes(x=TIME,y=VAR1)) 
   geom_point(color="blue",size=0.8) 
   facet_wrap(~ ID,nrow=3)
 fig2<-ggplot(data=simul[which(simul$ID >15),],
         aes(x=TIME,y=VAR1)) 
   geom_point(color="blue",size=0.8) 
   facet_wrap(~ ID,nrow=3)

I would like the individual plots in the last figure fig2 to be the same size than it fig1.

CodePudding user response:

You can do this by specifying the same number of rows and columns in both, with as.table = FALSE in fig2, but it will leave a lot of blank space:

fig2<-ggplot(data=simul[which(simul$ID >15),],
             aes(x=TIME,y=VAR1)) 
             geom_point(color="blue",size=0.8) 
             facet_wrap(~ ID,nrow=3, ncol=5, as.table=FALSE)

which produces

screenshot

This matches the individual panel sizes in fig1, but the label on the left is ugly, as is all the white space. I doubt if you can do anything about the white space (you asked for it by asking the plots to be smaller than they had to be!), but there's probably some tweak with labels etc. to fix the y-axis label placement, or just drop it with ylab(NULL).

CodePudding user response:

Here is another possibility, which gives a result which is really close from what I wanted, using ggdraw():

library("ggplot2")
library("cowplot")
nr<-3
nc<-5
a<-15
simul<-data.frame(ID=rep(1:20,5),
                  TIME=rep(1:5,each=20),
                  VAR1=runif(100,0,10))

fig1<-ggplot(data=simul[which(simul$ID <=a),],
             aes(x=TIME,y=VAR1)) 
  geom_point(color="blue",size=0.8) 
  facet_wrap(~ ID,nrow=nr,ncol=nc)

fig2<-ggplot(data=simul[which(simul$ID >a),],
             aes(x=TIME,y=VAR1)) 
  geom_point(color="blue",size=0.8) 
  facet_wrap(~ ID,nrow=nr,ncol=nc)

NB_ID<-length(unique(simul[which(simul$ID >a),"ID"]))
HEIGHT<-ceiling(NB_ID/nc)/nr 0.05
WIDTH<-ifelse(NB_ID>=nc,1,NB_ID/nc 0.05)
fig2_ok<- ggdraw()  
          draw_plot(fig2, x = 0, y = 1-HEIGHT, width = WIDTH, height = HEIGHT)
  • Related