python - PatchCollection 的 Matplotlib 颜色条覆盖颜色

标签 python matplotlib

我正在根据变量值中设置的值绘制补丁。

pc = PatchCollection(patches, match_original=True)  

norm = Normalize()
cmap = plt.get_cmap('Blues')
pc.set_facecolor(cmap(norm(values)))
ax.add_collection(pc)

enter image description here

现在我还想要一个额外的颜色条。如果我插话(例如在 set_facecolor 之前)

pc.set_array(values) # values
plt.colorbar(pc)

enter image description here

它有效,但现在所有颜色都变成了灰度。以下 set_facecolor 不会改变任何东西。即使我在 plt.colorbar() 中添加了 cmap= 命令,所有内容仍保持灰度。我不知道该怎么办。

最佳答案

您是在问如何通过特定的颜色图为集合着色吗?

只需设置颜色图 (cmap) 以及 array

例如:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection

num = 10
data = np.random.random((num, 2))
values = np.random.normal(10, 5, num)

# I'm too lazy to draw irregular polygons, so I'll use circles
circles = [plt.Circle([x, y], 0.1) for (x,y) in data]
col = PatchCollection(circles)

col.set(array=values, cmap='jet')

fig, ax = plt.subplots()

ax.add_collection(col)
ax.autoscale()
ax.axis('equal')

fig.colorbar(col)
plt.show()

enter image description here

解释你的问题是怎么回事:

对于集合,面部颜色要么手动设置(即 set_facecolors),要么将它们颜色映射到由颜色条控制的一系列值(set_array)。这两个选项是相互排斥的。因此,在您调用 set_array 后,原始面部颜色将被忽略。

关于python - PatchCollection 的 Matplotlib 颜色条覆盖颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24327704/

相关文章:

matplotlib - 如果我将 'tight' 用于 bbox_inches 和 fig.legend 方法,为什么生成的图像中不存在图例?

python - 将 numpy 数组保存为二进制以从 FORTRAN 读取

python - 从 pandas 数据框中的索引获取前后行

Python memory_profiler 不一致的绘图

python - 通过 django 中的 View 将 matplotlib 图形渲染为 html

python - 如何使用 matplotlib 设置 x 轴的时间间隔,例如 15 分钟

python - 如何为拆分的 y 轴制作 ax.twinx()?

python - Gaendb 结构化属性

python - Tensorflow 表查找 int->float

python-3.x - 每个轴标签的matplotlib颜色不同