title: Ordering bars in a stacked bar plot using ggplot
body: <p>The following is a simplified version of my dataframe (without too much loss in generality)</p>
  
  <pre><code>sales&lt;-data.frame(ItemID=c(1,3,7,9,10,12),
                    Salesman=c("Bob","Sue","Jane","Bob","Sue","Jane"),
                    ProfitLoss=c(10.00,9.00,9.50,-7.50,-11.00,-1.00))
  </code></pre>
  
  <p>which produces</p>
  
  <pre><code>  ItemID Salesman ProfitLoss
  1      1      Bob       10.0
  2      3      Sue        9.0
  3      7     Jane        9.5
  4      9      Bob       -7.5
  5     10      Sue      -11.0
  6     12     Jane       -1.0
  </code></pre>
  
  <p>The following produces a stacked bar plot of each salesman's sales, ordered by the overall profit for each salesman.</p>
  
  <pre><code>sales$Salesman&lt;-reorder(sales$Salesman,-sales$ProfitLoss,FUN="sum") #to order the bars
  profits&lt;-sales[which(sales$ProfitLoss&gt;0),]
  losses&lt;-sales[which(sales$ProfitLoss&lt;0),]
  ggplot()+
    geom_bar(data=losses,aes(x=Salesman, y=ProfitLoss),stat="identity", color="white")+
    geom_bar(data=profits,aes(x=Salesman, y=ProfitLoss),stat="identity", color="white")
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/VX39l.png" alt="enter image description here"></p>
  
  <p>This works exactly as I desire.  My issue arises when one of the salesmen has a profit but no loss, or a loss but no profit.  For instance, changing <code>sales</code> to </p>
  
  <pre><code>sales&lt;-data.frame(ItemID=c(1,3,7,9,10),
                    Salesman=c("Bob","Sue","Jane","Bob","Sue"),
                    ProfitLoss=c(10.00,9.00,9.50,-7.50,-11.00))
  </code></pre>
  
  <p>and reapplying the previous steps produces</p>
  
  <p><img src="https://i.stack.imgur.com/vC0I7.png" alt="enter image description here"></p>
  
  <p>So, the salesman are clearly out of order.  For this example I can cheat and plot my profits before losses like </p>
  
  <pre><code>ggplot()+
        geom_bar(data=profits,aes(x=Salesman, y=ProfitLoss),stat="identity", color="white")+
        geom_bar(data=losses,aes(x=Salesman, y=ProfitLoss),stat="identity", color="white")
  </code></pre>
  
  <p>but that won't work for my real dataset.</p>
  
  <p>Edit: In my real dataset, each salesman has more than two sales, and for each salesman I've stacked the bars so that the smallest bars in magnitude are closest to the x axis and the largest bars (i.e. biggest profit, biggest loss) are farthest from the x axis. For this reason, I need to call geom_bar() on both the <code>profits</code> dataframe and the <code>losses</code> dataframe. (I originally left this information out to try to avoid making my question too complex.)</p>