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

I saw Simon Jackson’s recent blog post regarding ordering categories within facets. He proposed a way of dealing with the problem of ordering variables shared across facets within facets. This problem becomes apparent in text analysis where words are shared across facets but differ in frequency/magnitude ordering within each facet. Julia Silge and David Robinson note that this is a particularly vexing problem in a TODO comment in their tidy text book: ## TODO: make the ordering vary depending on each facet ## (not easy to fix) Simon has provided a working approach but it feels awkward in that you are converting factors to numbers visually, adjusting spacing, and then putting the labels back on. I believe that there is a fairly straight forward tidy approach to deal with this problem.

## Terminology

Definitions of the terms I use to describe the solution:
• category variable – the bar categories variable (terms in this case)
• count variable – the bar heights variable
• facet variable – the meta grouping used for faceting

## Logic

I have dealt with the ordering within facets problem using this logic:
1. Order the data rows by grouping on the facet variable and the categories variable and arrange-ing on the count variable in a descending* fashion
2. Ungroup
3. Remake the categories variable by appending the facet label(s) as a deliminated suffix to the categories variable (make sure this is a factor with the levels reversed) [this maintains the ordering by making shared categories unique]
4. Plot as usual**
5. Remove the suffix you added previously using scale_x_discrete
*This allows you to take a slice of the top n terms if desired
**I prefer the ggstance geom_barh to the ggplot2 geom_bar + coord_flip as the former lets me set y as the terms variable and the later doesn’t always play nicely with scales being set free
This approach adds an additional 5 lines of code (in the code below I number them at as comment integers) and is, IMO, pretty easy to reason about. Here’s the additional lines of code:
group_by(word1, word2) %>%
arrange(desc(contribution)) %>%
ungroup() %>%
mutate(word2 = factor(paste(word2, word1, sep = "__"), levels = rev(paste(word2, word1, sep = "__")))) %>%
# --ggplot here--