I have a very annoying problem with a stacked bar plot created using ggplot2
.
There are a couple of similar questions previously asked but after going through
The order that bars are drawn (bottom to top) in a stacked barplot in ggplot2 is based on the ordering of the factor which defines the groups. So the Biogeographic.affinity factor must be reordered. Generally we use reorder
(if we want to order the factor according to a continuous levels) but here I will just create a new ordered factor similar to what you tried to do.
biogeo <- transform(biogeo,
Biog.aff.ord = factor(
Biogeographic.affinity ,
levels=c( 'Bassian','Widespread','Torresian', 'Eyrean'),
ordered =TRUE))
Now if you fill your barplot using Biog.aff.ord rather than the original factor and overriding the default grouping order by defining aes_group_order as Biog.aff.ord order you get the expected result:
cols <- c(Bassian="darkgrey",Widespread="lightgrey",
Torresian="white", Eyrean="black")
ggplot(data=biogeo, aes(x=Site, y=Percent,
order=Biog.aff.ord)) + ##!! aes_group_order
geom_bar(stat="identity", colour="black",
aes(fill=Biog.aff.ord)) +
scale_fill_manual(values = cols)