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

如何修改Hexbin图中单个单元格的填充颜色?

如何修改Hexbin图中单个单元格的填充颜色?

我希望微调Hexbin图中单个单元格的颜色,尝试使用PolyCollection的set_facecolors方法修改,但没有效果。示例代码本应生成中心为红色单元格的Hexbin图,代码如下:

import numpy as np
import matplotlib.pyplot as plt

x = y = np.linspace(0.,1.,10)
pts=np.vstack(np.meshgrid(x,y,indexing='ij')).reshape(2,-1).T
z = np.zeros_like(pts[:,0])

fig, ax = plt.subplots(figsize=(3, 3))
hb = ax.hexbin(pts[:,0],pts[:,1], C=z, gridsize=(5,3), vmin=-1., edgecolors='white')
ax.set_xlim([0,1])
ax.set_ylim([0,1])

ax.figure.canvas.draw()
fcolors = hb.get_facecolors()
fcolors[31] = [1., 0., 0., 1.]
hb.set_facecolors(fcolors)

plt.show()

预期效果:
Hexbin图中心红色单元格

解决方案

问题根源在于Hexbin对象默认会关联输入的C数组,每次绘制时都会根据C值和颜色映射重新计算单元格颜色,导致手动修改的facecolors被覆盖。只需在修改颜色后断开Hexbin与C数组的关联即可解决:

import numpy as np
import matplotlib.pyplot as plt

x = y = np.linspace(0.,1.,10)
pts=np.vstack(np.meshgrid(x,y,indexing='ij')).reshape(2,-1).T
z = np.zeros_like(pts[:,0])

fig, ax = plt.subplots(figsize=(3, 3))
hb = ax.hexbin(pts[:,0],pts[:,1], C=z, gridsize=(5,3), vmin=-1., edgecolors='white')
ax.set_xlim([0,1])
ax.set_ylim([0,1])

# 获取所有单元格的颜色数组
fcolors = hb.get_facecolors()
# 将索引31的单元格设为红色(RGBA格式)
fcolors[31] = [1., 0., 0., 1.]
# 应用修改后的颜色
hb.set_facecolors(fcolors)
# 关键:断开与C数组的关联,避免颜色被自动重新计算覆盖
hb.set_array(None)

plt.show()

如果你需要保留C数组的关联逻辑,也可以修改C数组中对应单元格的值,配合自定义颜色映射实现目标效果,但直接修改facecolors并断开数组关联的方式更直观高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:01:12