You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改corrplot相关性矩阵图图例文本颜色为白色的技术求助

问题

使用R语言的corrplot包绘制相关性矩阵图时,图中颜色图例的文本为黑色(对应上传图中红线标注部分),需要将其改为白色,现有代码如下:

# Load necessary libraries
library(ggplot2)
library(reshape2)
library(corrplot)

# Ensure that the dataset is not empty
if(nrow(dataset) > 0) {
    # Compute the correlation matrix
    cor_matrix <- cor(dataset, use = "complete.obs")
    
    # Increase plot size and adjust margins for better readability
    par(mar = c(4, 4, 2, 2), oma = c(2, 2, 2, 2), mfrow = c(1, 1))
    options(repr.plot.width=10, repr.plot.height=8)
    
    # Define custom color palette
    custom_col <- colorRampPalette(c("#8B0000", "#FFD700", "#006400"))(200)
    
    # Set plot background color and text color
    par(bg = "#003165", col.lab = "white", col.axis = "white", col.main = "white", col.sub = "white")
    
    # Plot the correlation matrix using corrplot with custom settings
    corrplot(cor_matrix, method = "color", type = "upper", 
             tl.col = "white", tl.srt = 45, 
             addCoef.col = "white", number.cex = 0.7,
             col = custom_col)
} else {
    plot.new()
    par(bg = "#003165")
    text(0.5, 0.5, "No data available", cex = 1.5, col = "white")
}

对应的相关性矩阵图:
相关性矩阵图

解决方法

在corrplot()函数中添加cl.text.col = "white"参数,该参数专门用于控制颜色图例的文本颜色。

修改后的核心代码片段

corrplot(cor_matrix, method = "color", type = "upper", 
         tl.col = "white", tl.srt = 45, 
         addCoef.col = "white", number.cex = 0.7,
         col = custom_col,
         cl.text.col = "white") # 新增参数,修改图例文本颜色

完整修改后的代码

# Load necessary libraries
library(ggplot2)
library(reshape2)
library(corrplot)

# Ensure that the dataset is not empty
if(nrow(dataset) > 0) {
    # Compute the correlation matrix
    cor_matrix <- cor(dataset, use = "complete.obs")
    
    # Increase plot size and adjust margins for better readability
    par(mar = c(4, 4, 2, 2), oma = c(2, 2, 2, 2), mfrow = c(1, 1))
    options(repr.plot.width=10, repr.plot.height=8)
    
    # Define custom color palette
    custom_col <- colorRampPalette(c("#8B0000", "#FFD700", "#006400"))(200)
    
    # Set plot background color and text color
    par(bg = "#003165", col.lab = "white", col.axis = "white", col.main = "white", col.sub = "white")
    
    # Plot the correlation matrix using corrplot with custom settings
    corrplot(cor_matrix, method = "color", type = "upper", 
             tl.col = "white", tl.srt = 45, 
             addCoef.col = "white", number.cex = 0.7,
             col = custom_col,
             cl.text.col = "white") # 修改图例文本颜色
} else {
    plot.new()
    par(bg = "#003165")
    text(0.5, 0.5, "No data available", cex = 1.5, col = "white")
}

添加该参数后,图例文本将变为白色,与深色背景适配。

内容的提问来源于stack exchange,提问作者Christian Bahnsen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 22:32:04