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

如何为散点矩阵添加匹配配色的类别标签图例?

问题描述

我在使用以下代码基于鸢尾花数据集绘制散点矩阵时,已按类别为散点设置了红、绿、蓝三种颜色:

from sklearn import datasets
import pandas as pd
import matplotlib.pyplot as plt
from numpy import array

iris = datasets.load_iris()

df = pd.DataFrame(iris.data, columns=iris.feature_names)
colors = array(50*['r']+50*['g']+50*['b'])
_ = pd.plotting.scatter_matrix(df, c=colors, figsize=[8,8], s=100, alpha=0.8)
plt.figure()

plt.imshow(X = [np.unique(iris.target)])
_ = plt.xticks(ticks=np.unique(iris.target),labels=iris.target_names)

当前散点矩阵效果

我希望添加与散点矩阵配色对应的类别标签图例,但尝试为plt.imshow()添加cmap参数时,根据Matplotlib官方文档说明,若X为RGB(A)格式该参数会被忽略;将X替换为colors变量后也无法实现预期效果,请问该如何解决?

解决方案

不用plt.imshow()来制作图例,直接通过Matplotlib的补丁模块手动创建匹配配色的图例元素,具体实现如下:

修改后完整代码

from sklearn import datasets
import pandas as pd
import matplotlib.pyplot as plt
from numpy import array
from matplotlib.patches import Patch

iris = datasets.load_iris()

df = pd.DataFrame(iris.data, columns=iris.feature_names)
colors = array(50*['r']+50*['g']+50*['b'])
# 绘制散点矩阵
axs = pd.plotting.scatter_matrix(df, c=colors, figsize=[8,8], s=100, alpha=0.8)

# 创建与散点配色对应的图例元素
legend_elements = [
    Patch(facecolor='r', label=iris.target_names[0]),
    Patch(facecolor='g', label=iris.target_names[1]),
    Patch(facecolor='b', label=iris.target_names[2])
]
# 将图例放在散点矩阵外侧,避免遮挡图表
plt.legend(handles=legend_elements, loc='upper right', bbox_to_anchor=(1.3, 1))

plt.show()

方案说明

  • 直接用Patch类创建对应颜色和类别的图例块,完全匹配散点矩阵的红、绿、蓝配色
  • 通过bbox_to_anchor参数可以灵活调整图例位置,避免遮挡散点矩阵内容
  • 逻辑简单直观,不需要依赖plt.imshow的复杂色彩映射规则

内容的提问来源于stack exchange,提问作者NELSON JOSEPH

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 11:16:12