setbackademic setbackademic - 29 days ago 15
R Question

Changing plotting order for stacked bar chart

I am trying to change the plotting order of groups in a stacked bar chart. Others have asked similar questions e.g. here and here but I can't seem to get anything similar to work.

Here is a toy example. I have a data frame with a number of sites, their latitude, and the number of mice, rats, rabbits and dogs at each of them. I would like to make a stacked bar chart with sites ordered by latitude on the y axis, and the number of animals on the x axis. I would like the animal bars plotted in a specific order (e.g. by size, smallest to largest).

I have written code that I think should work, but my effort to stipulate the plotting order for the animals only rearranges the legend, not the plot itself.

library(ggplot2)
df <- read.table(header=TRUE, text="site group taxa latitude
A mouse 2 -20
B rat 3 -17
C dog 6 -18
D rabbit 7 -24
A rabbit 2 -20
B mouse 5 -17
C rabbit 3 -18
D dog 2 -24
A dog 3 -20
B rabbit 4 -17
C mouse 3 -18
D mouse 2 -24")

plotOrder <- c("mouse","rat","rabbit","dog") #set the order in which I want to plot the groups
df$group <- factor(as.character(df$group), levels = plotOrder) #reorders the legend & colour, not plotting order

plot1 <-
ggplot(data = df,
aes(x=reorder(site, latitude), y=taxa, fill=group))+
geom_bar(aes(order = group), stat="identity") +
coord_flip()
plot1


Thanks in advance.

Answer

You can achieve this by ordering the whole data.frame:

plot1 <- 
  ggplot(data = df[order(df$site, df$group),], 
         aes(x=reorder(site, latitude), y=taxa, fill=group))+
  geom_bar(stat="identity") + 
  coord_flip()
plot1

enter image description here