Order of columns and rows with ggplot2 tile

2019-08-06 08:49发布

问题:

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:

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?

回答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))



标签: r ggplot2