如何使用crossprod()
和reshape2::melt()
:
m.h<-(matrix(sample(0:1,200,T),nrow=20))
m.cross<-matrix(unlist(lapply(1:nrow(m.h),function(x)crossprod(m.h[x,],t(m.h)))),nrow=nrow(m.h),byrow=T)
require(reshape2)
m.long<-melt(m.cross)
m.long[order(m.long$value,factor(m.long$Var2),factor(m.long$Var1)),]
require(ggplot2)
ggplot(m.long)+
geom_tile(aes(Var1,Var2,fill=value))+
geom_text(aes(Var1,Var2,label=value))+
theme(axis.text.x = element_text(angle = 90, hjust = 1))+
scale_fill_gradient(low="yellow",high="red") +
scale_x_discrete(breaks = 1:nrow(m.h), labels=unlist(lapply(1:nrow(m.h),function(x)paste0("Person ",x)))) +
scale_y_discrete(breaks = 1:nrow(m.h), labels=unlist(lapply(1:nrow(m.h),function(x)paste0("Person ",x)))) +
coord_cartesian(xlim=c(0,nrow(m.h)+1),ylim=c(0,nrow(m.h)+1))