How to align two plots with ggplot?

2019-05-29 03:48发布

问题:

I a trying to align two plots using grid but with no success. I have tried tweaking the themes so the plot border/size is the same but the plots do not align despite using the same y-coordinates. For the example below i could use annotation_custom (a few examples on site) but this limits the quantity of text I can add. Any suggestions / amendments / alternatives are appreciated.

My ugly code

library(gridExtra)
library(ggplot2)

# Data
my.df<-data.frame(vars=paste("variable",letters[1:8],sep="-"),   
  est=seq(-0.2,0.5,0.1),ci.l=seq(-0.2,0.5,0.1)-0.5,ci.u=seq(-0.2,0.5,0.1)+0.5)
my.df$effect<-with(my.df,paste(round(est,1),"(",round(ci.l,2)," ,",round(ci.u,2),")"))                  


# Functions                  

gg.forrest<-function(data, x , y , ymin, ymax , opts=NULL)        {        
 my.min<-floor(data[[ymin]])
 my.max<-ceiling(data[[ymax]])

p<- ggplot(data, aes_string(x=x, y=y, ymin=ymin, ymax=ymax)) + 
    geom_pointrange() + 
    geom_hline(aes(x=0), lty=2) + 
    theme( axis.title.y=element_blank(),axis.ticks.y = element_blank(), axis.text.y=element_text(colour = "black")) +
   coord_flip() +
   theme(axis.text.y=element_text(hjust=0, size=15)) +
   theme( plot.margin = unit(c(1,2,1,1), "lines")) +
   theme(panel.border = element_blank()   ,panel.background = element_blank()) +
   geom_segment(aes_string(y=my.min,yend=my.max,x=0,xend=0))  + 
   opts

  p
} 



gg.forest.text<-function(data, x, label, opts=NULL) {  

  p<- ggplot(data, aes_string(x=0, y=x, label=label)) +  
     geom_text( hjust=0, size=4, colour="black") + 
#    coord_flip() +
     theme_bw() + 
     theme(panel.grid.major = element_blank(), panel.border = element_blank()) +
#    theme(axis.title=element_blank(),axis.ticks = element_blank(), axis.text=element_blank()) +
    theme( axis.ticks = element_blank()) +
   scale_x_continuous( "",breaks=c(0),labels=c(" ")) +
   scale_y_discrete("",breaks=c(0),labels=c(" ")) +
   theme(plot.margin = unit(c(1,1,1,-3), "lines")) +
   opts

  p
}


# Output
p<-gg.forrest(my.df , "vars" , "est" , "ci.l" , "ci.u") 
p.eff<-gg.forest.text(my.df, "vars", "effect")

p.out<-arrangeGrob(p,p.eff,ncol=2 , widths=c(2,2/3))
print(p.out)

回答1:

I'd suggest the following,

library(gtable)
a <- ggplotGrob(p)
b <- ggplotGrob(p.eff)
grid.newpage()
grid.draw(gtable:::cbind_gtable(a, b, "first"))

but if you leave the default theme and margins of both plots, you'll notice that the alignment is still problematic, simply because the y values are not identical in both plot panels.



标签: r ggplot2 gtable