4

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!

Richard Telford
  • 9,558
  • 6
  • 38
  • 51
user971102
  • 3,005
  • 4
  • 30
  • 37
  • 1
    Does this answer your question? [Ordering stacks by size in a ggplot2 stacked bar graph](https://stackoverflow.com/questions/9227389/ordering-stacks-by-size-in-a-ggplot2-stacked-bar-graph) – tjebo Jan 25 '21 at 09:56
  • @tjebo I am not sure this is a duplicate of the target. This post is asking to reorder the fill within each bar. In contrast, the target is asking to reorder the fill across all bars. – Ian Campbell Jan 25 '21 at 14:13
  • @IanCampbell fair enough. I think it's worth to link the questions though :) – tjebo Jan 25 '21 at 14:21

1 Answers1

7

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

enter image description here

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58
  • This worked perfectly! Thank you so much Marco, I have been trying this for so long and didn't even think it was possible anymore! – user971102 Aug 13 '17 at 22:58