title: Ordering stacked bars in ggplot2
body: <p>I am trying to order the stacked bars in this bar chart in decreasing size. My issue is that my original dataframe undergoes quite a few operations to get it to the one that I pass to ggplot():</p>
  
  <pre><code>m %&gt;%
    group_by(Week, Pos) %&gt;%
    top_n(n = 5, wt = Points) %&gt;%
    ggplot(aes(x = dTeam)) +
    geom_bar(aes(fill = Pos), position = "stack") +
    xlab("Defensive Team") +
    ylab("Top 5 Weekly Scorers") +
    ggtitle("2015 DraftKings Total Top 5 Weekly Offensive Scorers per Defensive Team")
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/0DSvL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0DSvL.png" alt="enter image description here"></a>
  Generally, I understand using reorder to change the order hierarchy of one variable to another, but in this case I'm actually trying to change the order of dTeam to the total number of instances of each dTeam after:</p>
  
  <pre><code>m %&gt;%
    group_by(Week, Pos) %&gt;%
    top_n(n = 5, wt = Points)
  </code></pre>
  
  <p>The top of the original dataframe for reference:</p>
  
  <pre><code>  Team Week           Name   Opp. Points Salary Pos dTeam dSalary dPoints
  1  ari    1 Palmer, Carson v. nor  28.68   6500  QB   nor    2700       1
  </code></pre>
  
  <p>EDIT:
  I was able to get what I was looking for using this:</p>
  
  <pre><code>f &lt;- m %&gt;%
    group_by(Week, Pos) %&gt;%
    top_n(n = 5, wt = Points)
  
  f &lt;- within(f, 
        dTeam &lt;- factor(dTeam, 
            levels=names(sort(table(dTeam), 
                decreasing=TRUE))))
  f %&gt;%
    ggplot(aes(x = dTeam)) +
    geom_bar(aes(fill = Pos), position = "stack") +
    xlab("Defensive Team") +
    ylab("Top 5 Weekly Scorers") +
    ggtitle("2015 DraftKings Total Top 5 Weekly Offensive Scorers per Defensive Team")
  </code></pre>
  
  <p>I'm still wondering if there is a faster/easier way, though.</p>
  
  <p><a href="https://i.stack.imgur.com/9CDz7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9CDz7.png" alt="enter image description here"></a></p>