title: Order data for ggplot2 geom_tile
body: <p>I want to use create a heatmap of the following data in a heatmap:</p>
  
  <pre><code>IND1    IND2    FREQ
  Alix    Bob     3
  Bob     Crit    5
  Alix    Alix    7
  Fang    Fang    2
  Alix    Crit    1
  Crit    Dix     9
  Dix     Alix    2
  Bob     Fang    3
  Bob     Bob     1
  </code></pre>
  
  <p>I would also like to order the rows and columns according to the type of Individual. So, I have added 2 columns to the data to make it look as follows:</p>
  
  <pre><code>IND1    IND2    FREQ    IND1.TYPE   IND2.TYPE
  Alix    Bob     3       Dog         Cat
  Bob     Crit    5       Cat         Dog
  Alix    Alix    7       Dog         Dog
  Fang    Fang    2       Dog         Dog
  Alix    Crit    1       Dog         Dog
  Crit    Dix     9       Dog         Cat
  Dix     Alix    2       Cat         Dog
  Bob     Fang    3       Cat         Dog
  Bob     Bob     1       Cat         Cat
  </code></pre>
  
  <p>Essentially, I want the dogs to be grouped together and the Cats to be grouped together also along the X and Y axis. I am using the code from <a href="https://stackoverflow.com/questions/5713713/order-data-inside-a-geom-tile">this question</a> to do the ordering:</p>
  
  <pre><code>tr$IND1&lt;-factor(tr$IND1, levels=(tr$IND1)[order(tr$IND1.TYPE)])
  tr$IND2&lt;-factor(tr$IND2, levels=(tr$IND2)[order(tr$IND2.TYPE)])
  </code></pre>
  
  <p>The code for the heatmap is as follows:</p>
  
  <pre><code>ggplot(tr, aes(IND1, IND2)) + geom_tile(aes(fill = FREQ), colour = "white") + scale_fill_gradient(low = "blue", high = "red")
  </code></pre>
  
  <p>Which is producing the following plot:
  <a href="https://i.stack.imgur.com/fc3Vw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fc3Vw.jpg" alt="enter image description here"></a></p>
  
  <p>Though the Dogs and Cats are getting ordered in their respective groups, I would also want them to be alphabetically ordered inside their respective groups. So, I want the rows and columns to look like:</p>
  
  <pre><code>Fang
  Crit
  Alix
  Dix
  Bob
     Bob  Dix  Alix  Crit Fang
  </code></pre>
  
  <p>I was of the opinion that 'order' by default sorts alphabetically inside each group based on the accepted answer on <a href="https://stackoverflow.com/questions/36631775/ordering-rows-and-columns-of-r-matrix-by-criteria">this question</a> . But, this does not seem to work in this case.</p>
  
  <p>So, I was wondering about the most efficient way to do the ordering to get the desired output.</p>