klaskowski
klaskowski

Reputation: 11

Input own correlation matrix for corrplot

I would like to draw a correlation matrix graph, similar to what is output with corrplot.

However, I estimated my correlation matrix using a multivariate mixed model with MCMCglmm (because I wanted to account for a few fixed effects and some missing data points) so I would like to be able to input my own correlation matrix estimates (and associated confidence intervals) for corrplot to use. As far as I can tell, corrplot estimates the correlation matrix for you from your data - which I do not want it to do.

As an alternative to corrplot, I know I can build a correlation heatmap using ggplot and geom_tile. But I really like the 'ellipse' option that comes with corrplot.

library(reshape2)
library(corrplot)
library(ggplot2)

#my correlation matrix looks something like this
car.cor <- cor(mtcars)
melted_cormat <- melt(car.cor)
melted_cormat$upper <- melted_cormat$value+0.10
melted_cormat$lower <- melted_cormat$value-0.10

# with corrplot
car.cor <- cor(mtcars)
corrplot.mixed(car.cor, upper = "ellipse")

# with ggplot and geom_tile
ggplot(data = melted_cormat, aes(x=Var1, y=Var2, fill=value)) + 
  geom_tile()

So my questions are - how can I input my own correlation matrix for corrplot to use, or alternatively, how can I get the nice little ellipses using ggplot?

Upvotes: 0

Views: 1488

Answers (1)

markus
markus

Reputation: 26373

EDIT

Given your data

library(tidyverse)
library(reshape2)
library(corrplot)
library(magrittr)

car.cor <- cor(mtcars)
melted_cormat <- melt(car.cor)
melted_cormat$upper <- melted_cormat$value + 0.10
melted_cormat$lower <- melted_cormat$value - 0.10

you could do the following to generate a list of three matrices to be able to use corrplot

M <- melted_cormat %>% 
  gather(key, r, 3:5) %>% 
  spread(key = Var2, value = r) %>% 
  split(.$key) %>%
  map(., .f = set_rownames, value = NULL) %>%
  map(., .f = column_to_rownames, var = 'Var1') %>%
  map(., .f = select, -key) %>% 
  map(., as.matrix)

Now you can call corrplot with argument upp and low.

corrplot(M$value, low = M$lower, upp = M$upper, method = "ellipse")

enter image description here

It seems that this method does not display the confidence intervals. Compare this to the following plot.

corrplot(M$value, low = M$lower, upp = M$upper)

enter image description here

After some experimentation (n = 1) with the function corrplot.mixed things got out of hand

corrplot.mixed(corr = M$value, lower = "number", upper = "ellipse", low = M$lower, upp = M$upper)

enter image description here

I hope this helps.

Upvotes: 1

Related Questions