1
votes

I would like to generate a heatmap/correlation map in R. I have explored various packages, such as corrplot, ggcorrplot and pheatmap, but I found it difficult to get where I wanted.

As an example, using mtcars, I would like to generate a heatmap like below. Specifically:

  1. Compare mpg only against disp, hp, drat and wt using Spearman correlations.
  2. Do these comparisons for cyl=4, cyl=6 and cyl=8 separately.
  3. Calculate the Spearman p values.
  4. Draw heatmap, where tile colors represent Spearman correlation coefficients (r) and p values are printed on each tile.

Desired result similar to this: enter image description here

I would appreciate help. Thank you.

1

1 Answers

1
votes

You can do it with the psych package and a graphics package such as ggplot2 or pheatmap. First define a custom function to get the p-values, then apply the function with by.

library(psych)
myfun <- function(df) corr.test(df[, 1], df[, 3:6], method = "spearman", adjust = 
"none")$p

dfs <- by(mtcars, mtcars$cyl, myfun)
mat <- do.call(rbind, dfs)
rownames(mat) <- c("cyl = 4", "cyl = 6", "cyl = 8")

library(pheatmap)
pheatmap(mat, 
     cluster_rows = F, 
     cluster_cols = F, 
     display_numbers = T, 
     show_rownames = T,
     show_colnames = T,
     number_format = "%.4f")

heatmap

I haven't tried to exactly copy the heatmap above, but you can read ?pheatmap to learn about all its options.

Side note: If anyone can do this with the appropriate function in purrr piping into ggplot2 for the heatmap, you have my upvote.