问题描述
小提琴图 (b) 似乎与森林图 (a) 不太吻合。虽然第 5 列似乎对齐得很好,但所有其他列都没有。
我尝试了 plot_grid
、ggarange
、grid_draw
函数,但它们似乎无法解决对齐问题。
我的结果:
我的代码:
library(ggplot2)
library(cowplot)
#plots
a <- ggplot(data=dat_1,aes(x=varno,y=-coef,ymin=-LCI,ymax=-UCI))+
geom_errorbar(width=0,size = 2,color="steelblue")+
geom_point(size=5,color="steelblue")+
geom_hline(yintercept=0,color="black",linetype="dashed",alpha=.5)+ #add x=0 line
scale_y_continuous(name = "r")+
scale_x_continuous()+
ggtitle("A)")+
theme_minimal()+
theme(axis.text.x = element_blank(),axis.title.x = element_blank())
b <- ggplot(dat_2,aes(y=score,x=as.factor(group),fill=as.factor(time)))+
geom_violin(position=position_dodge(0.5),trim=T)+
scale_x_discrete()+
labs(fill = "time",y="ratings")+
ggtitle("B)")+
theme_minimal()+
theme(axis.text.x = element_text(angle = 90),axis.title.x = element_blank(),legend.position = "bottom")
plot_grid(a,b,align = "v",ncol = 1 )
我的数据:
#data
coef<-c(7.780000e-01,-2.350000e-01,-2.820000e-01,-3.090000e-01,7.560000e-01,-0.0210000,-2.000000e-01,-0.1790000000,-2.690000e-01,-0.10300000)
LCI<-c(7.240000e-01,-3.670000e-01,-3.940000e-01,-4.310000e-01,6.950000e-01,-0.1720000,-3.510000e-01,-0.3050000000,-4.290000e-01,-0.25600000)
UCI<-c( 8.280000e-01,-9.700000e-02,-1.450000e-01,-1.890000e-01,8.020000e-01,0.1240000,-6.480000e-02,-0.0369000000,-1.280000e-01,0.05850000)
varno<-1:10
dat_1<-data.frame(cbind(coef,LCI,UCI,varno))
dat_2<- data.frame(cbind(sample(1:5,10000,replace=T),rep(seq(1:10),1000)),c(rep(1,5000),rep(2,5000)))
colnames(dat_2)<-c("score","group","time")
解决方法
将 'varno' 更改为一个因子并去掉情节 A 上的 scale_x_continuous()
,您应该没问题,例如
library(ggplot2)
library(cowplot)
#data
coef<-c(7.780000e-01,-2.350000e-01,-2.820000e-01,-3.090000e-01,7.560000e-01,-0.0210000,-2.000000e-01,-0.1790000000,-2.690000e-01,-0.10300000)
LCI<-c(7.240000e-01,-3.670000e-01,-3.940000e-01,-4.310000e-01,6.950000e-01,-0.1720000,-3.510000e-01,-0.3050000000,-4.290000e-01,-0.25600000)
UCI<-c( 8.280000e-01,-9.700000e-02,-1.450000e-01,-1.890000e-01,8.020000e-01,0.1240000,-6.480000e-02,-0.0369000000,-1.280000e-01,0.05850000)
varno<-1:10
dat_1<-data.frame(cbind(coef,LCI,UCI,varno))
dat_2<- data.frame(cbind(sample(1:5,10000,replace=T),rep(seq(1:10),1000)),c(rep(1,5000),rep(2,5000)))
colnames(dat_2)<-c("score","group","time")
#plots
a<-ggplot(data=dat_1,aes(x=factor(varno),y=-coef,ymin=-LCI,ymax=-UCI))+
geom_errorbar(width=0,size = 2,color="steelblue")+
geom_point(size=5,color="steelblue")+
geom_hline(yintercept=0,color="black",linetype="dashed",alpha=.5)+ #add x=0 line
scale_y_continuous(name = "r")+
ggtitle("A)")+
theme_minimal()+
theme(axis.text.x = element_blank(),axis.title.x = element_blank())
b<-ggplot(dat_2,aes(y=score,x=factor(group),fill=factor(time)))+
geom_violin(position=position_dodge(0.5),trim=T)+
scale_x_discrete()+
labs(fill = "time",y="ratings")+
ggtitle("B)")+
theme_minimal()+
theme(axis.text.x = element_text(angle = 90),axis.title.x = element_blank(),legend.position = "bottom")
plot_grid(a,b,align = "v",ncol = 1 )