ggplot2按y轴比例对分类堆积的条形进行排序 [英] ggplot2 order categorical stacked bars by proportions of y-axis
问题描述
我有一个数据类别,该类别的x轴称为类别,y轴为丰度,由序列着色.对于每个类别,我都尝试按丰富程度对堆栈进行重新排序,以便可以轻松地看到哪个序列在底部的比例最高,而在顶部的比例最低.
目前,我可以制作如下条形图:
s<-序列丰度类别CAGTG 0.8 ACAGTG 0.2 BCAGTG 0.6摄氏度CAGTG 0.3 DCAGTG 0.1 EGGGAC 0.1 AGGGAC 0.1 BGGGAC 0.3摄氏度GGGAC 0.6丁GGGAC 0.1 ECTTGA 0.1 ACTTGA 0.7乙CTTGA 0.1摄氏度CTTGA 0.1 DCTTGA 0.8 Ed< -read.delim(textConnection(s),header = T,sep =")g = ggplot(d,aes(x =类别,y =丰度,填充=序列))+geom_bar(position ="fill",stat ="identity")
我的数据与此非常相似:
I have a data frame with categorical x-axis called Category and the yaxis is the Abundance, colored by Sequence. For each Category I am trying to reorder the stacks by the Abundance, so that it is easily visualized which sequence has the highest proportion at the bottom, to the lowest proportion at the top.
Currently, I can make a bar graph like this:
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")
My data is very similar to this: Ordering stacks by size in a ggplot2 stacked bar graph
But even trying to reproduce this solution (following the steps in the answer), it does not reorder the stacks by proportion:
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')
I cannot find an example for what I am looking for. Thanks so much for any help!
Use the group
aesthetic to control the order of the stacked bar.
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
这篇关于ggplot2按y轴比例对分类堆积的条形进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!