Search code examples
rggplot2geom-bar

r - reordering of barplot with ggplot2


Looking for how to reorder bars in ggplot2::geom_bar and none of the already posted answers helped solve the issue.

A reproducible example:

# sample dataframe
cf <- data.frame(a = rnorm(1000, mean = 50, sd = 50))

# just creating additional column to be used for grouping
cf <- cf %>% mutate(year = ifelse(row_number() <= 500, 2015, 2016))

#counting the occurences
cf <- cf %>% mutate(a = round(a, digits = 0)) %>% group_by(year, a) %>% count() %>% ungroup()

# plotting the result
ggplot(cf) + geom_bar(aes(reorder(a,-n),n), stat = "identity") + facet_wrap(~year)

The bars need to be from highest to lowest. There are many questions like this already posted but none of them solves this.

I tried the answer of this question: Reorder bars in geom_bar ggplot2 to produce the graph uploaded below, but this does not solve it and apparently the bars are still not reordered.

enter image description here


Solution

  • The problem in your data is that the level ordering between the two years 2015 and 2016 differs.

    When you split the data, reorder it separately and then use gridExtra to put them together, you get the desired result:

    df <- split(cf, cf$year)
    
    p <- lapply(df, function(x){
      ggplot(x) + geom_bar(aes(reorder(a, -n), n), stat = "identity")
    })
    
    library(gridExtra)
    grid.arrange(p[[1]], p[[2]], ncol = 2)
    

    Resulting plot:

    enter image description here