Site icon R-bloggers

How to reorder arrange bars with in each Facet of ggplot

[This article was first published on r-bloggers on Programming with R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
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

To leave a comment for the author, please follow the link and comment on their blog: r-bloggers on Programming with R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.