自定义相关图颜色

Customized correlation plot color

有什么方法可以自定义 R 中的相关图,例如下图

我想要不同的颜色值,例如,如果值介于 0.5 到 0.7 之间,则将其设为绿色,低于 0.7 则设为蓝色,高于 0.7 则设为红色

我使用下面的代码绘制相关图

library(corrplot)
data_matrix<-as.matrix(data)
corr_mat=cor(data_matrix,method="pearson")
corrplot(corr_mat,method = "number")

最好是 ggplot。自定义更容易。

如果需要,请使用 geom_text 内的附加参数 size 调整文本大小。

# given a correlation matrix
corr_matrix <- cor(mtcars)

library(dplyr)
library(tidyr)
library(ggplot2)

corr_matrix %>% 
  as_tibble(rownames = "var1") %>% 
  gather(var2, value, -var1) %>% 
  
  ggplot(aes(x = var1, y = var2, fill = value)) +
  geom_tile() +
  geom_text(aes(label = round(value, digits = 2))) +
  labs(x = "", y = "", fill = "Corr", title = "Correlation Matrix") +
  coord_fixed() +
  theme_minimal() +
  scale_fill_gradientn(
        limits = c(-1,1),

        # here choose the colours you want
        colours = c("blue", "green", "red"), 

        # here choose the intervals you want (must be inside rescale!)
        values = scales::rescale(c(-1, 0.5, 0.7, 1)))

只有数字[我个人会选择第一个]

corr_matrix %>% 
  as_tibble(rownames = "var1") %>% 
  gather(var2, value, -var1) %>% 
  
  ggplot(aes(x = var1, y = var2, colour = value)) +
  geom_tile(colour = "gray20", fill = "white") +
  geom_text(aes(label = round(value, digits = 2))) +
  labs(x = "", y = "", fill = "Corr", title = "Correlation Matrix") +
  coord_fixed() +
  theme_minimal() +
  scale_colour_gradientn(colours = c("blue", "green", "red"),
                       values = scales::rescale(c(-1, 0.5, 0.7, 1)),
                       limits = c(-1,1))


编辑

我添加这个是为了解决与标签排序相关的问题。

首先,我将编辑 mtcars 使其看起来像您的数据。

colnames(mtcars) <- paste0("Month", 1:11)
mtcars$Month12 <- rnorm(32)

好的,现在让我们继续看图。我们只需要添加一个小的编辑:我们将 var 名称作为有序因子。

corr_matrix <- cor(mtcars)

library(dplyr)
library(tidyr)
library(ggplot2)

corr_matrix %>% 
    as_tibble(rownames = "var1") %>% 
    gather(var2, value, -var1) %>% 
    
    # here is the additional line you need!
    mutate(across(c(var1, var2), factor, levels = paste0("Month", 1:12), ordered = TRUE)) %>% 
    
    ggplot(aes(x = var1, y = var2, fill = value)) +
    geom_tile() +
    geom_text(aes(label = round(value, digits = 2))) +
    labs(x = "", y = "", fill = "Corr", title = "Correlation Matrix") +
    coord_fixed() +
    theme_minimal() +
    scale_fill_gradientn(
        limits = c(-1,1),
        
        # here choose the colours you want
        colours = c("blue", "green", "red"), 
        
        # here choose the intervals you want (must be inside rescale!)
        values = scales::rescale(c(-1, 0.5, 0.7, 1)))

适用于 dplyr 版本 >= 1.0.0.

如果没有,请改用它:

  mutate_at(c("var1", "var2"), factor, levels = paste0("Month", 1:12), ordered = TRUE) %>%