业余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")

但我希望它看起来像这样,我手动模拟的:
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")

提前谢谢你!
更新:多亏了Roland,我有了一个图!然而,问题仍然存在于清晰度。对于那些对这里的代码和最终产品感兴趣的人:
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")

发布于 2013-06-29 16:50:36
这会更改顺序,而不会更改数据(就像您在模型中所做的那样)。其思想是创建一个有序(按Percent)因子,提供Age和ID之间的交互,并将其用于绘图,但将轴标签更改为仅匹配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")

然而,我认为由此产生的情节令人困惑,难以阅读。
发布于 2013-06-30 00:59:40
要理解的一个基本问题是,顺序是图形的属性还是数据本身的属性。R倾向于数据的属性,而不是绘图,因此绘图函数没有用于重新排序部分的参数,因为这应该在创建或编辑数据时完成。reorder函数是对因子水平进行重新排序的一种方法,可用于将来的图表/分析。
https://stackoverflow.com/questions/17374363
复制相似问题