r - 在数据框中按因素对堆积条形图进行排序

标签 r sorting ggplot2 stackedbarseries

这里是业余 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

最佳答案

这会在不更改数据的情况下更改顺序(就像您在模型中所做的那样)。这个想法是创建一个有序的(按 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

但是,我认为由此产生的情节令人困惑且难以阅读。

关于r - 在数据框中按因素对堆积条形图进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17374363/

相关文章:

r - 将长数据转化为广泛的使用频率

python - 如何按照键的排序顺序从字典中获取值?

r - 增加 geom_line 图的标签间距

R:Holt-Winters 每日数据(预测包)

r - 创建具有锐角的多边形不起作用

Java - 有序链表算法

php - 优化MYSQL+PHP父子输出

r - 如何在ggplot中为数字x轴的条形图添加直接标签

删除 ggplot2 中 geom_ribbon 的图例键周围的填充

r - 仅在 R 包中需要时才加载包