Skip to content

Instantly share code, notes, and snippets.

@bhive01
Created February 8, 2018 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhive01/061db9dc10cb49608d789b5745589e1d to your computer and use it in GitHub Desktop.
Save bhive01/061db9dc10cb49608d789b5745589e1d to your computer and use it in GitHub Desktop.
################################################
#Correlation matrix plot
raw.data <- raw.data[complete.cases(raw.data),]
c<-cor(raw.data[colstart:colend])
#Correlation p-value tests
cor.pvalues <- function(X){
nc <- ncol(X)
res <- matrix(0, nc, nc)
for (i in 2:nc){
for (j in 1:(i - 1)){
res[i, j] <- res[j, i] <- cor.test(X[,i], X[,j])$p.value
}
}
res
}
p <- cor.pvalues(raw.data[colstart:colend])
#convert p-values into stars for significance level
stars <- as.character(symnum(p, cutpoints=c(0,0.001,0.01,0.05,1),
symbols=c('***', '**', '*', '' ),
legend=FALSE,
))
#Combine into data.frame for plotting
molten.p<- melt(p)
molten.c<- melt(c)
molten.stars<- melt(stars)
molten.raw.data<-cbind(molten.c, molten.p[3], molten.stars[1])
#rename columns to avoid the same name
names(molten.raw.data) <- c("M1", "M2", "corr", "pvalue", "stars")
#define each triangle of the plot matric and the diagonal (mi.ids)
mi.ids <- subset(molten.raw.data, M1 == M2)
mi.lower <- subset(molten.raw.data[lower.tri(c),], M1 != M2)
mi.upper <- subset(molten.raw.data[upper.tri(c),], M1 != M2)
stars.lower <- subset(molten.raw.data[lower.tri(c),], M1 != M2)
meas <- as.character(unique(molten.raw.data$M2))
plot<-ggplot(molten.raw.data, aes(M1, M2, fill=corr))+
theme_bw()+
geom_tile(data=mi.lower) +
geom_text(data=mi.lower, aes(label=paste(stars)), size=1) +
geom_text(data=mi.ids, aes(label=M2), hjust=0, colour="grey40", size=1)+
scale_colour_identity() +
scale_fill_gradientn(colours= c("darkblue", "lightblue", "white", "pink", "darkred"), limits=c(1,-1)) +
scale_x_discrete("", limits=meas[length(meas):1]) + #flip the x axis
scale_y_discrete("", limits=meas)+
theme(axis.text.x = element_text(angle=90, hjust=1, vjust=0.5))+
guides(fill=F, colour=F)
ggsave("cor.matrix.plot.png", width=cor.size, height=cor.size)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment