ggplot2 按 y 轴的比例排序分类堆积条

ggplot2 order categorical stacked bars by proportions of y-axis

我有一个名为 Category 的分类 x 轴数据框,yaxis 是丰度,按序列着色。对于每个类别,我都试图按丰度对堆栈重新排序,以便很容易看出哪个序列在底部的比例最高,在顶部的比例最低。

目前,我可以制作这样的条形图:

s<-"Sequence Abundance Category
CAGTG 0.8 A
CAGTG 0.2 B
CAGTG 0.6 C
CAGTG 0.3 D
CAGTG 0.1 E
GGGAC 0.1 A
GGGAC 0.1 B
GGGAC 0.3 C
GGGAC 0.6 D
GGGAC 0.1 E
CTTGA 0.1 A
CTTGA 0.7 B
CTTGA 0.1 C
CTTGA 0.1 D
CTTGA 0.8 E"

d<-read.delim(textConnection(s),header=T,sep=" ")

g = ggplot(d,aes(x = Category, y = Abundance, fill = Sequence)) + 
      geom_bar(position = "fill",stat = "identity")

我的数据与此非常相似:Ordering stacks by size in a ggplot2 stacked bar graph

但即使尝试重现此解决方案(按照答案中的步骤),它也不会按比例重新排序堆栈:

d$Sequence <- reorder(d$Sequence, d$Abundance)
d$Sequence <- factor(d$Sequence, levels=rev(levels(d$Sequence)))
ggplot(d, aes(x=Category, y=Abundance, fill=Sequence)) + 
  geom_bar(stat='identity') 

我找不到我要查找的示例。非常感谢您的帮助!

使用 group 美学来控制堆叠栏的顺序。

s <- "Sequence Abundance Category
CAGTG 0.8 A
CAGTG 0.2 B
CAGTG 0.6 C
CAGTG 0.3 D
CAGTG 0.1 E
GGGAC 0.1 A
GGGAC 0.1 B
GGGAC 0.3 C
GGGAC 0.6 D
GGGAC 0.1 E
CTTGA 0.1 A
CTTGA 0.7 B
CTTGA 0.1 C
CTTGA 0.1 D
CTTGA 0.8 E"  
d <- read.delim(textConnection(s), header=T, sep=" ")

# Add the "group" aesthetic to control the order of the stacked bars
g = ggplot(d,aes(x=Category, y=Abundance, fill=Sequence, group=Abundance)) + 
    geom_bar(position = "fill",stat = "identity")
g