使用ggplot在相关热图上排序x轴

时间:2013-12-05 03:26:41

标签: r ggplot2

我正在尝试使用ggplot创建相关热图,但我似乎无法控制x或y轴上变量的顺序。特别是,ggplot似乎尝试按顺序排序变量,但只对第一个数字进行操作。这是一个简单的问题示例

x1<-c(1,2,3,4,5,6,6,7,4,5,6,3,4,5,6,7,8,9)

x2<-c(1,2,3,3,5,4,6,7,4,4,6,3,4,5,6,10,8,9)

x3<-c(2,2,3,5,5,4,6,4,4,4,6,3,4,5,6,10,8,9)

x4<-c(1,2,3,5,5,4,6,4,4,4,4,4,4,5,6,10,8,9)

x5<-c(1,2,3,3,5,4,6,7,4,4,6,3,4,5,6,10,8,9)

x10<-c(1,1,1,1,1,1,6,1,1,1,1,1,4,5,1,1,1,1)

new=data.frame(x1)

new$x2=x2

new$x3=x3

new$x4=x4

new$x5=x5

new$x10=x10

keep=melt(cor(new))

ggplot(keep,aes(Var1,Var2),xlab=NULL,ylab=NULL) + geom_tile(aes(fill = value),colour = "white") + scale_fill_gradient(low = "white",high = "steelblue")+theme(axis.title.x=element_blank(),axis.title.y=element_blank())

如果您运行此代码,您将看到x轴已订购

x1, x10, x2, x3, x4, x5 

而我希望它阅读

x1, x2, x3, x4, x5, x10

有没有办法指定这个顺序?

3 个答案:

答案 0 :(得分:1)

这对我有用:

keep$Var1 <- factor(keep$Var1, levels = unique(keep$Var1), ordered = TRUE)
keep$Var2 <- factor(keep$Var2, levels = unique(keep$Var2), ordered = TRUE)

ggplot(keep,aes(Var1,Var2),xlab=NULL,ylab=NULL) + geom_tile(aes(fill = value),colour = "white") + scale_fill_gradient(low = "white",high = "steelblue")+theme(axis.title.x=element_blank(),axis.title.y=element_blank())

enter image description here

答案 1 :(得分:0)

对于此特定示例,一个选项是命名变量x01x02等,然后他们将正确排序。

答案 2 :(得分:0)

如果填充零解决方案不适合您的目的,请尝试此操作:

cust_breaks<-unique(keep$Var1[order(as.numeric(gsub("x","",keep$Var1)))])

ggplot(keep,aes(Var1,Var2),xlab=NULL,ylab=NULL) + 
  geom_tile(aes(fill = value),colour = "white") + 
  scale_fill_gradient(low = "white",high = "steelblue") + 
  theme(axis.title.x=element_blank(),axis.title.y=element_blank()) +
  scale_x_discrete(limits=cust_breaks) + 
  scale_y_discrete(limits=cust_breaks)
相关问题