Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.

If you’re intereted more in Data Visualziation, Here’s Datacamp Paid Course with 75% Annual Offer