-1

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

adl
  • 1,390
  • 16
  • 36
  • Thank you for your comment but I already mentioned that the solutions (like the one for this answer) did not solve my problem – adl Jun 20 '18 at 10:03
  • 1
    Please explain further which solutions from other questions you have tried and what exactly did not work. The plot looks pretty ordered already. – LAP Jun 20 '18 at 10:04
  • many of the suggestions in similar questions did not fix the error in ordering of the bars shown above. An image of the current ordered barplot is uploaded in the question and I believe it is obvious that not all of the bars are ordered accordingly to size of the n column. The code to reproduce this plot is also included in the question, while I tried converting the n column to factor and character first it didn't fix the ordering – adl Jun 20 '18 at 10:11
  • @LAP thank you for your comment, but from what I can see the bars are not ordered, and after all it is either ordered or not ordered. "pretty ordered" is not something I'm looking for – adl Jun 20 '18 at 10:23
  • @LAP this produces an error. Is it possible to see this comment in an answer format? – adl Jun 20 '18 at 10:59
  • @adl I'm working on a solution, will post an answer if I'm getting anywhere. – LAP Jun 20 '18 at 10:59

1 Answers1

1

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

LAP
  • 6,605
  • 2
  • 15
  • 28