Search code examples
rsortingggplot2percentagestacked-bar-chart

How can I re-order my percent stacked barchart in R based on descending stack segment height?


I'm trying to order the bars of my percent stacked barchart in R based on descending stack segment height. R automatically sorts my categorical data in alphabetical order (in both the barchart and its legend) but I'd like the data to be ordered so to have the biggest bars (the ones with the greatest stack segment height) on top of the barchart and the smallest at the bottom, in a descending manner. I don't know how to do this because I cannot manually set a specific order with a vector prior to using ggplot2: my dataset is quite big and I need it to be ordered based on total field area (a quantitative variable that changes for every single city I'm considering). Does anyone know hot to help me?


Solution

  • You need to set your categorical variable as an ordered factor. For example, using the iris data, the default is for an alphabetical x-axis:

    iris%>%
      ggplot(aes(Species,Petal.Length))+
      geom_col()
    

    enter image description here

    Using fct_reorder (from forecats, included in the tidyverse), you can change a character variable to a factor and give it an order in one step. Here I change the order of the x-axis such that is order by the average sepal width of the petal.

    iris%>%
      mutate(Species=fct_reorder(Species,Sepal.Width,mean))%>%
      ggplot(aes(Species,Petal.Length))+
      geom_col()
    

    enter image description here