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

如何为分块矩阵的不同子块设置独立cmap实现可视化区分

分块矩阵各子块独立设置cmap的实现方案

核心思路:无需直接渲染完整的合并矩阵,分别对每个子块调用imshow,通过extent参数控制子块在画布上的位置,即可为每个子块指定独立的颜色映射。

完整实现代码如下:

import numpy as np
import matplotlib.pyplot as plt

# 生成示例子矩阵,和你的输入一致
x = np.random.random((2,2))
xx = np.random.random((3,3))
y = np.random.random((2,3))
zz = np.block([
    [x, y],
    [y.T, xx]
])

# 可选配置:如果需要全局统一数值到颜色的映射规则,先计算全局极值
# 不需要全局统一的话可以删除这两行,每个子块会根据自身数值范围渲染
global_vmin = zz.min()
global_vmax = zz.max()

fig, ax = plt.subplots()

# 绘制左上角子块x,指定cmap为Reds
ax.imshow(x, cmap='Reds', extent=[0, x.shape[1], x.shape[0], 0],
          vmin=global_vmin, vmax=global_vmax)
# 绘制右上角子块y,指定cmap为Blues
ax.imshow(y, cmap='Blues', extent=[x.shape[1], x.shape[1]+y.shape[1], y.shape[0], 0],
          vmin=global_vmin, vmax=global_vmax)
# 绘制左下角子块y.T,指定cmap为Greens
ax.imshow(y.T, cmap='Greens', extent=[0, y.T.shape[1], zz.shape[0], x.shape[0]],
          vmin=global_vmin, vmax=global_vmax)
# 绘制右下角子块xx,指定cmap为Purples
ax.imshow(xx, cmap='Purples', extent=[x.shape[1], zz.shape[1], zz.shape[0], x.shape[0]],
          vmin=global_vmin, vmax=global_vmax)

# 调整坐标轴适配完整矩阵尺寸
ax.set_xlim(0, zz.shape[1])
ax.set_ylim(zz.shape[0], 0)

# 可选:添加白色分割线更清晰地区分子块
ax.axvline(x=x.shape[1], color='white', linewidth=2)
ax.axhline(y=x.shape[0], color='white', linewidth=2)

plt.show()

相关注意事项:

  • 每个子块的cmap可替换为任意matplotlib支持的颜色映射
  • 如果子块数量较多,可提前将所有子块的尺寸、位置、对应cmap存入列表,用循环批量调用imshow即可,无需手动编写每个子块的渲染代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:39:01