Skip to content

Instantly share code, notes, and snippets.

@mattwigway
Created February 22, 2014 19:47
Show Gist options
  • Save mattwigway/9161103 to your computer and use it in GitHub Desktop.
Save mattwigway/9161103 to your computer and use it in GitHub Desktop.
Draw visual correlation plots
# Draw visual correlation plots, http://www.indicatrix.org/2014/02/22/visual-correlation-matrices/
# Copyright (C) 2014 Matthew Wigginton Conway.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
library(ggplot2)
library(scales)
corplot <- function(data, title=NA) {
# We save two copies because we'll be monkeying with the cors matrix to make the colors
# right
cors <- ret <- cor(data)
# Principal diagonal: show white so text is visible
diag(cors) <- 0
label <- matrix(as.character(round(cors, 2)), nrow(cors), ncol(cors))
diag(label) <- names(data)
df <- data.frame(x=rep(1:ncol(cors), nrow(cors)), y=-sort(rep(1:nrow(cors), ncol(cors))),
r=as.vector(cors), label=as.vector(label))
p <- ggplot(df)
# default color scheme inspired by color scheme in The Elements of Statistical Learning, by
# Hastie, Tibshirani and Friedman.
p <- p + scale_fill_gradient2(lim=c(-1, 1), low=muted('orange'), high=muted('blue')) +
geom_raster(mapping=aes(x, y, fill=r)) +
geom_text(mapping=aes(x, y, label=label)) +
theme(axis.title=element_blank(), axis.text=element_blank(),
axis.line=element_blank(), axis.ticks=element_blank(),
panel.border=element_blank())
if (!is.na(title)) {
p <- p + ggtitle(title)
}
benchplot(p)
return(cors)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment