<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/ordering-categories-within-ggplot2-facets-2/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://trinkerrstuff.wordpress.com/2016/12/23/ordering-categories-within-ggplot2-facets/"> R – TRinker's R Blog</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>I saw Simon Jackson’s <a target="_blank" rel="nofollow" href="https://drsimonj.svbtle.com/ordering-categories-within-ggplot2-facets">recent blog post</a> 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. <a target="_blank" rel="nofollow" href="https://twitter.com/juliasilge">Julia Silge</a> and <a target="_blank" rel="nofollow" href="https://twitter.com/drob">David Robinson</a> note that this is a particularly vexing problem in a TODO comment in their tidy text book:</p>
<p><code>## TODO: make the ordering vary depending on each facet<br>
## (not easy to fix)</code></p>
<p><a target="_blank" rel="nofollow" href="http://imgur.com/iLSLioq"><img title="source: imgur.com" width="80%" src="https://i0.wp.com/i.imgur.com/iLSLioq.png"></a></p>
<p>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.</p>
<h2>Terminology</h2>
<p>Definitions of the terms I use to describe the solution:</p>
<ul>
<li><strong>category variable</strong> – the bar categories variable (terms in this case)</li>
<li><strong>count variable</strong> – the bar heights variable</li>
<li><strong>facet variable</strong> – the meta grouping used for faceting</li>
</ul>
<h2>Logic</h2>
<p>I have dealt with the ordering within facets problem using this logic:</p>
<ol>
<li>Order the data rows by grouping on the facet variable and the categories variable and <code>arrange</code>-ing on the count variable in a descending* fashion</li>
<li>Ungroup</li>
<li>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]</li>
<li>Plot as usual**</li>
<li>Remove the suffix you added previously using <code>scale_x_discrete</code> </li>
</ol>
<p><span><em>*This allows you to take a slice of the top n terms if desired</em><br><em>**I prefer the <strong><a target="_blank" rel="nofollow" href="https://github.com/lionel-/ggstance">ggstance</a></strong> <code>geom_barh</code> to the <strong>ggplot2</strong> <code>geom_bar</code> + <code>coord_flip</code> as the former lets me set y as the terms variable and the later doesn’t always play nicely with scales being set free</em></span></p>
<p>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:</p>
<pre>
group_by(word1, word2) %>%                  
arrange(desc(contribution)) %>%                
ungroup() %>%
mutate(word2 = factor(paste(word2, word1, sep = &quot;__&quot;), levels = rev(paste(word2, word1, sep = &quot;__&quot;)))) %>% 
    # --ggplot here--
    scale_x_discrete(labels = function(x) gsub(&quot;__.+$&quot;, &quot;&quot;, x)) 
</pre>
<h2>Example</h2>
<p>Let’s go ahead and use Julia and David’s example to demonstrate the technique:</p>
<pre>
# Required libraries
p_load(tidyverse, tidytext, janeaustenr)

# From section 5.1: Tokenizing by n-gram
austen_bigrams &lt;- austen_books() %>%
    unnest_tokens(bigram, text, token = &quot;ngrams&quot;, n = 2)

# From section 5.1.1: Counting and filtering n-grams
bigrams_separated &lt;- austen_bigrams %>%
    separate(bigram, c(&quot;word1&quot;, &quot;word2&quot;), sep = &quot; &quot;)

	
# From section 5.1.3: Using bigrams to provide context in sentiment analysis
AFINN &lt;- get_sentiments(&quot;afinn&quot;)
negation_words &lt;- c(&quot;not&quot;, &quot;no&quot;, &quot;never&quot;, &quot;without&quot;)

negated_words &lt;- bigrams_separated %>%
    filter(word1 %in% negation_words) %>%
    inner_join(AFINN, by = c(word2 = &quot;word&quot;)) %>%
    count(word1, word2, score, sort = TRUE) %>%
    ungroup()


# Create plot
negated_words %>%
    mutate(contribution = n * score) %>%
    mutate(word2 = reorder(word2, contribution)) %>%
    group_by(word1) %>%
    top_n(10, abs(contribution)) %>%
    group_by(word1, word2) %>%                                    #1
    arrange(desc(contribution)) %>%                               #2
    ungroup() %>%                                                 #3
    mutate(word2 = factor(paste(word2, word1, sep = &quot;__&quot;), levels = rev(paste(word2, word1, sep = &quot;__&quot;)))) %>% #4
    ggplot(aes(word2, contribution, fill = n * score > 0)) +
        geom_bar(stat = &quot;identity&quot;, show.legend = FALSE) +
        facet_wrap(~ word1, scales = &quot;free&quot;) +
        xlab(&quot;Words preceded by negation&quot;) +
        ylab(&quot;Sentiment score * # of occurrences&quot;) +
        theme_bw() +
        coord_flip() +
        scale_x_discrete(labels = function(x) gsub(&quot;__.+$&quot;, &quot;&quot;, x)) #5
</pre>
<p><a target="_blank" rel="nofollow" href="http://imgur.com/QvZ3ADz"><img title="source: imgur.com" width="80%" src="https://i2.wp.com/i.imgur.com/QvZ3ADz.png"></a></p>
<p> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/trinkerrstuff.wordpress.com/2057/"><img alt="" src="http://feeds.wordpress.com/1.0/comments/trinkerrstuff.wordpress.com/2057/" border="0"></a> <img alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" border="0" data-recalc-dims="1"></p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://trinkerrstuff.wordpress.com/2016/12/23/ordering-categories-within-ggplot2-facets/"> R – TRinker's R Blog</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/lzFHW9jUdqI"></a></div>