Search code examples
rggplot2geom-bar

Sort bars according to y-value


I have a dataset with two variables:

  • district: factor w/ 26 levels (A, B, C, D etc.)
  • type: "x", "o" (factor)

Now I'd like to plot a stacked barplot: One bar for each year.

ggplot(aes(x = district, fill=type), data=dat) + geom_bar()

My problem is, that the bars should be in ascending order (of the total of each district). Like this:

  |
  |  x
  |  x
  |  x  x
n |  o  x  x
  |  o  o  o
  |  o  o  o  x
  |  o  o  o  o 
  _______________
     A  C  G  B …

Does anyone know how to do this?


Solution

  • Here is a reprex for your data:

    district <- sample(LETTERS, 1000, replace = TRUE)
    xo <- c("x","o")
    type <- sample(xo, 1000, replace = TRUE)
    

    Here is your df. You need to create a count column that you can order your districts by.

    library(tidyverse)
    
    df <- as.data.frame(cbind(district, type)) %>%
      group_by(district) %>%
      mutate(count = n())
    

    Within your aes argument, you can specify reorder district, by descending count:

    ggplot(df, aes(x = reorder(district, -count), fill=type)) +
      geom_bar()
    

    And if you don't want to alter your df by grouping or adding a count variable, you can do this:

    df %>%
      group_by(district) %>%
      mutate(count = n()) %>%
      ggplot(aes(x = reorder(district, -count), fill=type)) +
      geom_bar()