定制的相关图颜色

问题描述

是否可以自定义R中的相关图,例如下面的图

enter image description here

我想具有不同的颜色值,例如,如果值介于0.5到0.7之间,则将其设置为绿色,将其设置为绿色,将其设置为蓝色,将其设置为0.7以下,将其设置为红色

我在下面的代码中使用了相关图

=

解决方法

最好使用ggplot。自定义更容易。

如果需要,可以在size中使用附加参数geom_text来调整文本的大小。

# 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)))

enter image description here

只需加上数字[我个人会选择第一个]

corr_matrix %>% 
  as_tibble(rownames = "var1") %>% 
  gather(var2,colour = value)) +
  geom_tile(colour = "gray20",fill = "white") +
  geom_text(aes(label = round(value,title = "Correlation Matrix") +
  coord_fixed() +
  theme_minimal() +
  scale_colour_gradientn(colours = c("blue",values = scales::rescale(c(-1,1)),limits = c(-1,1))

enter image description here


编辑

我添加了此标签是为了解决与标签排序有关的问题。

首先,我将编辑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,-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,fill = value)) +
    geom_tile() +
    geom_text(aes(label = round(value,digits = 2))) +
    labs(x = "",title = "Correlation Matrix") +
    coord_fixed() +
    theme_minimal() +
    scale_fill_gradientn(
        limits = c(-1,1)))

enter image description here

它适用于{= {1}}版本> = 1.0.0。

如果您没有它,请改用它:

dplyr