2013-06-28 42 views
2

业余R用户在这里。我在网上看起来很难,看看这个问题是否已被回答/询问,但我还没有找到一个好的答案。我无法发布图片,因为我没有10个“声望”​​在数据框中按因子排序堆积条形图

我想要一个堆积条形图,它根据摄取路线的贡献百分比(按降序)对x变量进行排序。

Percent<-c(0.4,0.75,0.8, 0.3,0.1,0.6,0.25,0.5) 
Inh<-data.frame(ID=c(rep(1,4),rep(2,4)),Age=factor(rep(1:4,2), label=c("0-1 year", "1-2 years", "2-3 years","3-6 years")), Route=factor(rep(1), label="Inhalation"), Percent=Percent) 

Ing<-data.frame(ID=c(rep(1,4),rep(2,4)),Age=factor(rep(1:4,2), label=c("0-1 year", "1-2 years", "2-3 years","3-6 years")), Route=factor(rep(1), label="Ingestion"),  Percent=1-Percent) 

df<-data.frame(rbind(Inh,Ing)) 
ggplot(df,aes(x=ID,y=Percent,fill=Route))+ geom_bar(stat="identity")+ 
facet_wrap(~Age, scales = "free_x") + 
ylab("Percent Contribution") + 
labs(title = "Route Contribution to Exposure by Age Groups") 

enter image description here

但我希望它看起来像这样,我手动嘲笑了:

Percent<-c(0.1,0.6,0.25, 0.3,0.4,0.75,0.8,0.5) 
Inh<-data.frame(ID=c(rep(1,4),rep(2,4)),Age=factor(rep(1:4,2), label=c("0-1 year", "1-2 years", "2-3 years","3-6 years")), Route=factor(rep(1), label="Inhalation"), Percent=Percent) 

Ing<-data.frame(ID=c(rep(1,4),rep(2,4)),Age=factor(rep(1:4,2), label=c("0-1 year", "1-2 years", "2-3 years","3-6 years")), Route=factor(rep(1), label="Ingestion"),  Percent=1-Percent) 

df<-data.frame(rbind(Inh,Ing)) 
ggplot(df,aes(x=ID,y=Percent,fill=Route))+ geom_bar(stat="identity")+ 
facet_wrap(~Age, scales = "free_x") + 
ylab("Percent Contribution") + 
labs(title = "Route Contribution to Exposure by Age Groups") 

enter image description here

预先感谢您!

更新:感谢罗兰,我有一个情节!虽然问题仍然清晰。对于那些有兴趣在这里的代码和最终产品:

ggplot(df,aes(x=id2,y=Percent,fill=Route, width=1,order = -as.numeric(Route)))+ 
geom_bar(stat="identity")+ 
facet_wrap(~Age, scales = "free_x") + 
xlab(" ")+ 
ylab("Percent Contribution") + 
theme(axis.text.x = element_blank(), axis.ticks.x= element_blank()) + 
labs(title = "DEHP Route Contribution to Exposure by Age Groups") 

enter image description here

+1

对于图片,你可以把它作为链接,并有更高的声誉的人可以添加它。 – agstudy

+0

在线放置图像或图像:即您的输入提供给您的图像和模拟您希望产生的图像。 –

回答

1

这改变了顺序不改变数据(如你在实物模型做)。这个想法是创建一个有序的(由Percent)因子给出AgeID的交互作用并将其用于绘图,但更改轴标签以仅匹配ID值。

df <- df[order(df$Route,df$Percent),] 
df$id2 <- factor(paste(df$ID,df$Age),levels=unique(paste(df$ID,df$Age)),ordered=TRUE) 

ggplot(df,aes(x=id2,y=Percent,fill=Route))+ 
    geom_bar(stat="identity")+ 
    scale_x_discrete(labels = setNames(regmatches(levels(df$id2),regexpr("[[:alnum:]]*",levels(df$id2))),levels(df$id2))) + 
    facet_wrap(~Age, scales = "free_x") + 
    xlab("ID") + 
    ylab("Percent Contribution") + 
    labs(title = "Route Contribution to Exposure by Age Groups") 

enter image description here

不过,我认为所产生的情节混乱,难以阅读。

+0

@ Roland-谢谢!您的解决方案奏效是的,我认为这些情节在提交时需要一些解释。我已经与这个情节和并排的盒子情节来回走动。任何额外的建议,将不胜感激。再次感谢。 – LeslieKish

0

要理解的一个基本问题是订单是图的属性还是数据本身的属性。 R倾向于数据的属性而不是图形,因此绘图函数没有用于重新排序零件的参数,因为在创建或编辑数据时应该完成这些参数。 reorder函数是对未来图形/分析中使用的因子级别进行重新排序的一种方法。