ggplot2: Changing the order of stacks on a bar graph

This might be a solution.

What I did was ordering the dataset, so that the value I wanted to appear closest to the x-axis appeared first in the dataset. (I’ve used your ordering of factors here). This fixt the positioning of the bars.

Then, we had to change the colors and order of the legend. I could not wrap my head around scale_fill_grey, so I changed it to scale_fill_manual instead, setting both values and breaks.

ggplot(all_is2[rev(order(all_is2$developed)),] ,aes(x=agriculture,y=acres,fill=developed))+
  geom_bar(position="stack", stat="identity")+theme_bw()+
  facet_wrap(~islands)+ 
  scale_fill_manual(values=c(developed="grey80",available="grey20"),name="",
                    breaks=c("developed","available"))+
 xlab("")+ylab("Acres")

enter image description here

I don’t know if it’s a bug or a feature, and I think this also happened with previous versions in ggplot, but it appears that with stat_identity the first observation is plotted closest to the x-axis, the second on top of that etc.

Demonstration:

set.seed(123)
testdat <- data.frame(x=1,y=sample(5))


p1 <- ggplot(testdat, aes(x=x,y=y,fill=factor(y))) +geom_bar(stat="identity")+labs(title="order in dataset")
p2 <- ggplot(testdat[order(testdat$y),],aes(x=x,y=y,fill=factor(y))) +
  geom_bar(stat="identity") + labs(title="ordered by y")
p3 <- ggplot(testdat[rev(order(testdat$y)),],aes(x=x,y=y,fill=factor(y))) +
  geom_bar(stat="identity") + labs(title="reverse ordered by y")

enter image description here

Leave a Comment