Distance ggplot geom_tile with faces

I am trying to make a faceted ggplot sorted by two discrete variables along the x axis. The problem is that I would like to see all adjacent records vertically touching each other. Currently, there is a gap between the lines, based on what levels of the factor are in the upper section relative to the bottom. Sorry, this reproducible example is a bit detailed.

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 to do is to remove all the vertical space between the lines of both the top and bottom graph (face). For example, since identifier number 15 is in the control group, the treatment group should not have a row for it. Thanks Seth

+4
source share
1 answer
 library("grid") p + opts(panel.margin=unit(0,"pt")) 

EDIT: after further clarification

Invalid space removed. You want to change your call to facet_grid to include the 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

+11
source

Source: https://habr.com/ru/post/1400471/


All Articles