title: How to order subgroups in a ggplot barplot?
body: <p>I would like to order the groups in both the legend and plot of a ggplot created with geom_bar.</p>
  
  <p>Here is an example</p>
  
  <pre><code>mydata &lt;- data.frame(mygroup = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'), 
                       mysubgroup = c("north", "west", "south", "east", "north", "west", "south", "east"), 
                       value = c(5,10,6,12, 4, 4, 3, 5))
  </code></pre>
  
  <p>My starting point:</p>
  
  <pre><code>myplot &lt;- ggplot(mydata, aes(mygroup, value, fill = mysubgroup)) + 
              geom_bar(position = "dodge", width = 0.5, stat = "identity")
  myplot
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/6Ybnq.png" alt="enter image description here"></p>
  
  <p>I would like to have both the legend and the bars plotted in the order "north", "south", "east", "west".</p>
  
  <p>I have tried adding <code>scale_fill_discrete(limits = c("north", "south", "east", "west"))</code> to the plot. It puts the legend in the desired order, but not the bars (although the bars are rearranged).</p>
  
  <pre><code>myplot + scale_fill_discrete(limits = c("north", "south", "east", "west"))
  </code></pre>
  
  <p>even if I reorder the data, I get the same result as above: </p>
  
  <pre><code>mydata2 &lt;- mydata[c(1,3,4,2,5,7,8,6),]
  myplot2 &lt;- ggplot(mydata2, aes(mygroup, value, fill = mysubgroup)) + 
                 geom_bar(position = "dodge", width = 0.5, stat = "identity") 
  myplot2 + scale_fill_discrete(limits = c("north", "south", "east", "west"))
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/2y4Dt.png" alt="enter image description here"></p>