Reputation: 1
I would like to reorder the bars in a stacked bay plot based on the values within a bar. My data is percentage male contribution to a nest so all of the bars sum to one. What I would like to do is order the bars based on the contribution from the third male.
My data looks like this
Nest.ID Percentage Male
6_2012 0.611111111 Primary
6_2012 0.222222222 Secondary
6_2012 0.166666667 Tertiary
7_2012 0.46875 Primary
7_2012 0.3125 Secondary
7_2012 0.21875 Tertiary
and I am creating my graph with this code:
m <- ggplot()+geom_bar(aes(y=Percentage, x=Nest.ID,
fill=forcats::fct_rev(Male)),
data=males,stat="identity")
I have tried to use the reorder function but have run into issues because all the nests sum to one and the value I would like to order by "Tertiary Male" is a factor within a column.
Upvotes: 0
Views: 49
Reputation: 145775
reorder
works well when you are doing a relatively simple function of a single variable for the order. You're doing something a little more specific and depending on two variables, so I would just pull the order and set it explicitly.
my_order = with(males[males$Male == "Tertiary", ], as.character(Nest.ID[order(Percentage)]))
males$Nest.ID = factor(males$Nest.ID, levels = my_order)
As a side note, use geom_col(...)
instead of geom_bar(..., stat = "identity")
.
Upvotes: 1