R 自定义相关图颜色

R 自定义相关图颜色,r,correlation,pearson-correlation,r-corrplot,ggcorrplot,R,Correlation,Pearson Correlation,R Corrplot,Ggcorrplot,有没有办法自定义R中的相关图,例如下图 我希望有不同的颜色值,例如,如果值在0.5到0.7之间,则将其设置为绿色,低于此值时,将其保持为蓝色,高于0.7时,将其保持为红色 我用下面的代码做相关图 library(corrplot) data_matrix<-as.matrix(data) corr_mat=cor(data_matrix,method="pearson") corrplot(corr_mat,method = "number")

有没有办法自定义R中的相关图,例如下图

我希望有不同的颜色值,例如,如果值在0.5到0.7之间,则将其设置为绿色,低于此值时,将其保持为蓝色,高于0.7时,将其保持为红色

我用下面的代码做相关图

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

库(corrplot)

数据矩阵最好是
ggplot
。它更容易定制

如果需要,可以使用附加参数
size
inside
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)))


编辑

我添加此选项是为了解决与标签排序相关的问题

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

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

你需要素色还是渐变色?你是说绝对值是0.5和0.7吗?或者你希望所有底片都是蓝色的?您需要显示数字还是仅显示正方形/圆圈?可能重复。你看过答案了吗?谢谢江户,我真的很感激这个解决方案,我能够生成绘图,但标签不同步,例如,应该是Month1,Month2。。。。按这个顺序是12个月。生成@Edo的绘图的图像链接,尝试使用重新排序,但标签没有安排好。你能帮我吗。下面是我尝试过的,但是在添加了重新排序的ggplot(aes(x=reorder(var1,desc(-var1)),y=reorder(var2,desc(var2)),fill=value))链接之后,它没有得到正确的ggplot(aes(x=reorder(var1,-desc(var1)),y=reorder(var2,desc(var2)),fill=value))好的,看看我的编辑。您需要将其转换为一个因子,并手动对级别进行排序。这就是方法。获取跨越中的错误(c(var1,var2),factor,levels=paste0(“月”,1:12),:找不到函数“跨越”
colnames(mtcars) <- paste0("Month", 1:11)
mtcars$Month12 <- rnorm(32)
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)))

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