Search code examples
rggplot2bar-chart

Ordering the bars in a bar chart with multiple grouping variables


Here is a MWE.

df <- data.frame(Y = c(1:12),
                 Combination = c(1,1,2,2,3,3,4,4,5,5,6,6),
                 Treatment = c("AX", "AY", "AY", "AX", 
                               "BZ", "BY", "BZ", "BX", 
                               "BY", "BX", "BX", "BY"),
                 Stage = rep(c(1,2), 6)
                      )

For this data, I want to create a bar chart where the x-axis is grouped by Combination, the bars are filled by Treatment, and within each combination, I want the bars to be ordered by stage.

The following is my code which can only achieve the first two conditions. I searched for some solutions, but they didn't work well for this particular dataset.

my_greys <- c("#000000", "#707070", "#000000","#707070", "#CCCCCC")

ggplot(test.df, aes(y = Y, fill = factor(Treatment), x = Combination  ) ) +
   geom_bar(position='dodge', stat='summary', fun='mean', show.legend = T) +
   theme_classic() + 
   scale_fill_manual(values = my_greys)

The Bar Chart

My purpose: I want the bars (filled by Treatment) in each Combination are ordered by the Stage variable.


Solution

  • Use the group aesthethic, e.g. like so:

    ggplot(test.df, aes(factor(Combination), Y, fill = factor(Treatment), group = Stage)) +
      geom_bar(position='dodge', stat='summary', fun='mean')
    

    enter image description here