How to reorder arrange bars with in each Facet of ggplot

One of the problems that we usually face with ggplot is that rearranging the bars in ascending or descending order. If that problem is solved using reorder() or fct_reorder(), the next problem is when we have facets and ordering bars within each facet.

Recently I came acrosss this function reorder_within() from the package tidytext (Thanks to Julia Silge and Tyler Rinker - who created this solution originally)

Example Code:

library(tidyr)
library(ggplot2)

iris_gathered <- gather(iris, metric, value, -Species)

ggplot(iris_gathered, aes(reorder(Species, value), value)) +
  geom_bar(stat = 'identity') +
  facet_wrap(~ metric)

As you can see above, the bars in the last facet isn’t ordered properly. This is a problem you wouldn’t forget had you plotted TF_IDF or something similar with facets.

Here’s the solution

library(tidytext)
# reorder_within and scale_x_reordered work.
# (Note that you need to set scales = "free_x" in the facet)
ggplot(iris_gathered, aes(reorder_within(Species, value, metric), value)) +
   geom_bar(stat = 'identity') +
  #scale_x_reordered() +
  facet_wrap(~ metric, scales = "free_x")

Now, that’s beautifully done with a change in function.

 
comments powered by Disqus