Matplotlib中PatchCollection的colorbar覆盖颜色

4 投票
1 回答
2854 浏览
提问于 2025-04-18 10:29

我正在根据一个叫做 values 的变量里的数值来绘制一些图形。

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= 的命令,颜色依然是灰色的。我不知道该怎么解决这个问题。

1 个回答

6

你是在问怎么用特定的颜色映射给一组东西上色吗?

只需要设置颜色映射(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()

在这里输入图片描述

来解释一下你问题中的内容:

对于一组东西,它们的颜色可以手动设置(也就是用set_facecolors),或者根据一个值的范围来上色(用set_array),这个范围是由一个颜色条控制的。这两种方法不能同时使用。所以,一旦你调用了set_array,之前设置的颜色就会被忽略。

撰写回答