Frank Robertson
Frank Robertson

Reputation: 3

How can I include multiple colours in the text labels for a correlation matrix in R corrplot?

So I'm trying to create a correlation matrix using R's corrplot package. I would like to use two colours in the text labels, to show to groups of variables.

As a simple example:

dat <- data.frame("Blue" = c(1:20), "Red" = sample(1:20, 20, replace = T))

dat <- as.matrix(dat)

C = rcorr(dat, type = "pearson")

corrplot(corr = C$r, order = "original", title = "Pearson Correlations", method = "color", type = "full", p.mat=C$P, insig = "blank", tl.col = "blue", addgrid.col = "darkgrey", bg = "white", cl.pos = "b", tl.pos = "tl", col = colorRampPalette(c("darkred","white","midnightblue"))(100), mar = c(4, 0, 4, 0))

I know that tl.col is the argument for title colour, but I would like to change the two variables to have different colours from each other, and can't find this option in the docs. Is this possible?

Upvotes: 0

Views: 1243

Answers (1)

Indrajeet Patil
Indrajeet Patil

Reputation: 4879

You can just use combine function c() to input different color labels for different columns.

library(corrplot)
library(Hmisc)

# defining dataframe
dat <-
  data.frame("Blue" = c(1:20),
             "Red" = sample(1:20, 20, replace = T))

# getting correlations
C = Hmisc::rcorr(as.matrix(dat), type = "pearson")

# preparing the plot
corrplot::corrplot(
  corr = C$r,
  order = "original",
  title = "Pearson Correlations",
  method = "color",
  type = "full",
  p.mat = C$P,
  insig = "blank",
  tl.col = c("blue", "red"), # different colors
  addgrid.col = "darkgrey",
  bg = "white",
  cl.pos = "b",
  tl.pos = "tl",
  col = colorRampPalette(c("darkred", "white", "midnightblue"))(100),
  mar = c(4, 0, 4, 0)
)

Created on 2018-02-20 by the reprex package (v0.2.0).

Upvotes: 1

Related Questions