Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot geom_tile spacing with facets

Tags:

r

ggplot2

I am trying to make a faceted ggplot sorted by two discrete variables on the x axis. The problem is that I would like to have the vertically adjacent entries all touching. Currently there is space between rows based on which levels of the factor are in the top plot vs bottom. sorry this reproducible example is a bit verbose.

npats=20   

simsympt=c(id=1,date=1,tx="control",sympt=0) 

for(i in 1:npats)

 {   days=abs(round(rnorm(1,100,40),0))
     id=rep(as.character(i),days)
     date=1:days
     tx=rep(sample(c("control","treatment"),1),days)
     sympt= sample(0:10, days,p=c(12,3,3,2,1,1,1,1,1,1,1),rep=T)

   simsympt=      rbind(simsympt,      cbind(id,date,tx,sympt) )
  }
       ####tidy things up a bit   
     simsympt=data.frame(simsympt)[-1,]
     colnames(simsympt)=c('id','date','tx','level')
     simsympt$date=as.numeric(as.character(simsympt$date))
     simsympt$level=as.numeric(as.character(simsympt$level))
     #simsympt$id=as.numeric(as.character(simsympt$id))

  head(simsympt)

##now the important stuff

 p <- ggplot(simsympt, aes(x=date,y=id))    
 p=   p + geom_tile(aes(fill=level)) +   
      facet_grid(tx~.,drop=T,space="free")+
      scale_y_discrete(expand=c(0,0),drop=T)
 p

No description here

All I need is to remove the all the vertical space between rows in both the top and the bottom graph(facet). For example, since id number 15 is in the control group there should not be a row for her in the treatment group. Thanks, Seth

like image 851
Seth Avatar asked Mar 08 '12 21:03

Seth


1 Answers

library("grid")
p + opts(panel.margin=unit(0,"pt"))

EDIT: after further clarification

Removed the wrong space. What you want is to change your facet_grid call to include a scales="free" argument.

p <- ggplot(simsympt, aes(x=date,y=id))    
p=   p + geom_tile(aes(fill=level)) +   
     facet_grid(tx~.,drop=T,space="free",scales="free")+
     scale_y_discrete(expand=c(0,0),drop=T)

enter image description here

like image 186
Brian Diggs Avatar answered Nov 03 '22 00:11

Brian Diggs