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
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With