Search code examples
rggplot2bar-chartfillstacked-chart

Ordering the 'fill' of a stacked bar chart ggplot2


Is there a way for me to order my stacked barchart by the variable The_Number_Of_Evaders rather than having to manually input the levels I would like? The current results of the graph can be found here

The_Number_Of_Evaders <- c(287, 76, 237, 44, 249, 149, 3)

The_Results_Of_Using_The_Line <- c('Allied servicemen reached Spain through the Pyrenees', 'Civilians reached Spain through the Pyrenees',
 'Airmen who were arrested during their evasion', 'Airmen who were handed over to other evasion lines',
 'Airmen who were kept in camps of the "Operation Marathon" in France and Belgium', 
 'Airmen who were hidden by their lodgers until Liberation', 
 'Airmen who were killed during their evasion')

Line <- rep("Comete", 7)

Comete_Line <- data.frame(The_Number_Of_Evaders, The_Results_Of_Using_The_Line, Line)

Comete_Line_Ordered <- Comete_Line[order(Comete_Line$The_Number_Of_Evaders),]

Comete_Line_Ordered %>%
  ggplot(aes(x = Line, y = The_Number_Of_Evaders, fill = The_Results_Of_Using_The_Line)) + 
  geom_bar(stat = "identity", width = 0.5)

Solution

  • Try one of this options. You can use reorder() with fill:

    library(ggplot2)
    library(dplyr)
    #Code 1
    Comete_Line %>% ggplot(aes(x = Line,
                               y = The_Number_Of_Evaders,
                               fill = reorder(The_Results_Of_Using_The_Line,-The_Number_Of_Evaders))) +
      geom_bar(stat = "identity", width = 0.5)+
      labs(fill='Var')
    

    Output:

    enter image description here

    Or this:

    #Code 2
    Comete_Line %>% ggplot(aes(x = Line,
                               y = The_Number_Of_Evaders,
                               fill = reorder(The_Results_Of_Using_The_Line,The_Number_Of_Evaders))) +
      geom_bar(stat = "identity", width = 0.5)+
      labs(fill='Var')
    

    Output:

    enter image description here