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

Python中使用PatchCollection时如何将0设为颜色中心?

让圆形热力图颜色条中心对齐0(对应白色)

你用PatchCollection实现的圆形热力图,默认颜色映射未以0为中心,导致RdBu_r色板的白色中间色没有对应到0值。可以通过设置归一化规则解决这个问题,具体步骤如下:

关键修改思路

PatchCollection本身没有center参数,但可以借助matplotlib.colors.CenteredNorm指定颜色映射的中心值为0,强制让0对应色板的中间白色。

修改后的完整代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.colors import CenteredNorm  # 新增导入归一化类

N = 10
M = 11
ylabels = [''.join(np.random.choice(list("PQRSTUVXYZ"), size=7)) for _ in range(N)]
xlabels = [''.join(np.random.choice(list("ABCDE"), size=3)) for _ in range(M)]

x, y = np.meshgrid(np.arange(M), np.arange(N))
s = np.random.randint(0, 180, size=(N,M))
c = np.random.rand(N, M)-0.6

fig, ax = plt.subplots(figsize=(7, 5))

R = s/s.max()/2
circles = [plt.Circle((j,i), radius=r) for r, j, i in zip(R.flat, x.flat, y.flat)]
# 新增norm参数,将颜色映射中心固定为0
col = PatchCollection(circles, array=c.flatten(), cmap="RdBu_r", norm=CenteredNorm(center=0))
ax.add_collection(col)

ax.set(xticks=np.arange(M), yticks=np.arange(N),
       xticklabels=xlabels, yticklabels=ylabels)
ax.set_xticks(np.arange(M+1)-0.5, minor=True)
ax.set_yticks(np.arange(N+1)-0.5, minor=True)
ax.grid(which='minor')

fig.colorbar(col)
plt.show()

补充说明

  • CenteredNorm(center=0)会将颜色映射的中心牢牢固定在0,无论你的数据c正负分布是否对称,都能让0值对应RdBu_r的白色中间点。
  • 如果数据存在极端异常值,可替换为SymLogNorm实现对数对称的颜色映射,但CenteredNorm更适配线性分布的常规场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:02:31