重新排序ggplot2中的方面

时间:2015-03-17 00:17:56

标签: r ggplot2 facet

我已经通过示例更改了网站上的方面订单,但似乎无法为我的具体案例提供任何帮助。任何有关如何使用我的数据设置执行此操作的想法将非常感激。我对ggplot2有些新意,并且非常难过。我希望我的模型可以在每个方面的顶部订购M1,M2,M3和M1。谢谢!

Outcome<-c(1,1,1,2,2,2,3,3,3)
OR<-c(1.97,2.47,3.56,1.73,2.25,4.09,1.21,1.48,2.25)
min<-c(1.37,1.74,2.55,1.13,1.52,2.84,0.74,0.95,1.49)
max<-c(2.83,3.49,4.98,2.66,3.35,5.9,1.97,2.33,3.41)
Aces<-c(1,2,3,1,2,3,1,2,3)
ace<-data.frame(cbind(Outcome,OR,min,max,Aces))

ace_labels <- list('1'="1 ACE",'2'="2 ACEs",'3'="3 ACEs")

ace_labeller <- function(variable,value){return(ace_labels[value])}

ace$Outcome = factor(ace$Outcome, levels=c("1","2","3"), 
                 labels=c("M1: Depression","M2: MH Barrier to Work",
                          "M3: MH Barrier to Work"))            

ggplot(data=ace,aes(x=OR,y=Outcome,label=OR))+
geom_point(aes(size=8))+
geom_text(size=5,vjust=1.8)+
geom_errorbarh(aes(xmin=min,xmax=max),height=.1)+
geom_vline(xintercept=1,linetype="dashed")+
scale_x_log10(breaks=seq(1,6,1),name="Figure 1: Odds Ratios (OR) and 95% Confidence Intervals for Models 1, 2 and 3 (N=1073)
            \nEach OR is compared to 0 ACEs")+
labs(y="")+
facet_grid(Aces~., labeller=ace_labeller)+
guides(size=FALSE)+
theme_bw()+
theme(axis.text.y=element_text(size=12))+
theme(strip.text.y=element_text(size = 12))+
theme(axis.title.x=element_text(face="italic", size = 12,hjust=.5))

enter image description here

1 个答案:

答案 0 :(得分:1)

如果你反转你为ace$Outcome设置的标签,你可以在每个方面的底部,M2和M3上绘制M1。

只需改变:

ace$Outcome = factor(ace$Outcome, levels=c("3","2","1"), 
             labels=c("M3: MH Barrier to Work",
                      "M2: MH Barrier to Work",
                      "M1: Depression"))

使用您生成的相同样本数据和绘图代码:

enter image description here

您的代码(仅更改了上述内容):

Outcome<-c(1,1,1,2,2,2,3,3,3)
OR<-c(1.97,2.47,3.56,1.73,2.25,4.09,1.21,1.48,2.25)
min<-c(1.37,1.74,2.55,1.13,1.52,2.84,0.74,0.95,1.49)
max<-c(2.83,3.49,4.98,2.66,3.35,5.9,1.97,2.33,3.41)
Aces<-c(1,2,3,1,2,3,1,2,3)
ace<-data.frame(cbind(Outcome,OR,min,max,Aces))

ace_labels <- list('1'="1 ACE",'2'="2 ACEs",'3'="3 ACEs")

ace_labeller <- function(variable,value){return(ace_labels[value])}

ace$Outcome = factor(ace$Outcome, levels=c("3","2","1"), 
                 labels=c("M3: MH Barrier to Work",
                          "M2: MH Barrier to Work",
                          "M1: Depression"))            

library(ggplot2)

ggplot(data=ace,aes(x=OR,y=Outcome,label=OR))+
geom_point(aes(size=8))+
geom_text(size=5,vjust=1.8)+
geom_errorbarh(aes(xmin=min,xmax=max),height=.1)+
geom_vline(xintercept=1,linetype="dashed")+
scale_x_log10(breaks=seq(1,6,1),name="Figure 1: Odds Ratios (OR) and 95% Confidence Intervals for Models 1, 2 and 3 (N=1073)
            \nEach OR is compared to 0 ACEs")+
labs(y="")+
facet_grid(Aces~., labeller=ace_labeller)+
guides(size=FALSE)+
theme_bw()+
theme(axis.text.y=element_text(size=12))+
theme(strip.text.y=element_text(size = 12))+
theme(axis.title.x=element_text(face="italic", size = 12,hjust=.5))