1

I have this code:

library(ggplot2)

tableau.m <- melt(tableau)

ggplot(tableau.m, aes(variable, Name)) + 
      geom_tile(aes(fill = value), colour = "white") + 
      scale_fill_distiller(palette = "Spectral") +
      theme(axis.text.x = element_text(angle = 270))

with tableau:

Name,NGO,A,E,D,C
NGO,10,5,14,3,0
A,5,21,6,1,0
E,14,6,19,6,4
D,3,1,6,7,1
C,0,0,4,1,3

Which give me this:

enter image description here

Now, this is an adjacency matrix, and I need for rows and columns to meet on the diagonal. For some reason rows are ordered alphanumerically while columns kept their original order.

How can I fix this?

tonytonov
  • 25,060
  • 16
  • 82
  • 98
Lucien S.
  • 5,123
  • 10
  • 52
  • 88
  • 2
    Both name and variable are a factor. (with different ordering in the level). You'll need to reorder them. – Heroka Oct 22 '15 at 08:17
  • I thought I saw you answered your own question, but it's gone now. You can either use reorder in ggplot, or change factor levels in the dataset used for plotting. – Heroka Oct 22 '15 at 20:33
  • I though my answer ggplot(tableau.m, aes(x=reorder(variable,value), y=reorder(Name,value))) worked, but there still are problems on bigger datasets: reordering by values mixed up some columns. I'm now trying to ordering in alphabetical order... Any clue on how to do that in ggplot with reorder? – Lucien S. Oct 22 '15 at 20:38
  • See my answer- it gets the order right before plotting. – Heroka Oct 22 '15 at 20:54

1 Answers1

1

Here's an answer you could try. I have refactored things outside of ggplot. This is a personal preference, as I like to be able to check things and I've made many mistakes with it in the past.

#set vector of levels you want
mylevels <- tableau$Name

#reorder factors
tableau.m$Name <- factor(tableau.m$Name,levels=mylevels)
tableau.m$variable <- factor(tableau.m$variable, levels=mylevels)

#plot
ggplot(tableau.m, aes(variable, Name)) + 
  geom_tile(aes(fill = value), colour = "white") + 
  scale_fill_distiller(palette = "Spectral") +
  theme(axis.text.x = element_text(angle = 270))

enter image description here

Heroka
  • 12,889
  • 1
  • 28
  • 38