我试图使用对齐两个图grid
但没有成功。我尝试调整主题,使绘图边框/大小相同,但尽管使用相同的 y 坐标,但绘图并没有对齐。对于下面的示例,我可以使用annotation_custom
(现场有几个示例),但这限制了我可以添加的文本数量。任何建议/修正/替代方案表示赞赏。
我丑陋的代码
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)