0

I want to use create a heatmap of the following data in a heatmap:

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

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:

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

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 this question to do the ordering:

tr$IND1<-factor(tr$IND1, levels=(tr$IND1)[order(tr$IND1.TYPE)])
tr$IND2<-factor(tr$IND2, levels=(tr$IND2)[order(tr$IND2.TYPE)])

The code for the heatmap is as follows:

ggplot(tr, aes(IND1, IND2)) + geom_tile(aes(fill = FREQ), colour = "white") + scale_fill_gradient(low = "blue", high = "red")

Which is producing the following plot: enter image description here

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:

Fang
Crit
Alix
Dix
Bob
   Bob  Dix  Alix  Crit Fang

I was of the opinion that 'order' by default sorts alphabetically inside each group based on the accepted answer on this question . But, this does not seem to work in this case.

So, I was wondering about the most efficient way to do the ordering to get the desired output.

Community
  • 1
  • 1
DotPi
  • 3,977
  • 6
  • 33
  • 53
  • Sounds like you want to order by, e.g., `IND1.TYPE` and `IND1`, not just `IND1.TYPE`. Like `levels = unique(tr$IND1[order(tr$IND1.TYPE, tr$IND1)])` – aosmith Apr 15 '16 at 16:38
  • @aosmith : Can you add that as an answer? it worked for me. So I will accept the answer. – DotPi Apr 15 '16 at 18:28

1 Answers1

0

In order to keep your factors ordered alphabetically within the Dog/Cat groups you will need to order the levels based on both the variables.

tr$IND1 <- factor(tr$IND1, levels = unique(tr$IND1[order(tr$IND1.TYPE, tr$IND1)]))
tr$IND2 <- factor(tr$IND2, levels = unique(tr$IND2[order(tr$IND2.TYPE, tr$IND2)]))

Then your plot axes will have the desired order.

enter image description here

aosmith
  • 34,856
  • 9
  • 84
  • 118