具有ggplot2图块的列和行的顺序 [英] Order of columns and rows with ggplot2 tile

查看:116
本文介绍了具有ggplot2图块的列和行的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

  library(ggplot2)

tableau.m< - (tableau)

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

与图表:

 名称,非政府组织,A,E,D,C 
非政府组织,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

其中给我这个:





现在,这是一个邻接矩阵,我需要行和列在对角线上相遇。由于某些原因,行以字母数字顺序排列,而列保持其原始顺序。



我该如何解决这个问题?

解决方案

这是您可以尝试的答案。我已经重构了ggplot之外的东西。这是一种个人偏好,因为我喜欢能够检查一些事情,过去我犯过很多错误。

 #你想要的
的水平向量$ b $ mylevels< - tableau $名称

#reorder因子
tableau.m $名称< - 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),color =white)+
scale_fill_distiller(palette =Spectral)+
theme(axis.text。 x = element_text(angle = 270))


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?

解决方案

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

这篇关于具有ggplot2图块的列和行的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆