首页 > 解决方案 > 将 cmap 设置为 Matplotlib PatchCollection

问题描述

我有一个由多个多边形(三角形)组成的补丁集合。每个三角形都有一个整数值。我想根据三角形的不同值为该补丁集合设置一个颜色映射。

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib

X = np.linspace(0,10,5)
Y = np.linspace(0,10,5)
values = [np.random.randint(0,5) for i in range(0,5)]

fig, ax = plt.subplots()

s = 2   # Triangle side
patches = []

# Creating patches --> How could I insert here 'value' variable? For taking it into account in cmap.
for x,y,value in zip(X,Y,values):
    tri = matplotlib.patches.Polygon(([(x      ,       y     ),
                                       (x + s/2, y - 0.866 * s),
                                       (x - s/2, y - 0.866 * s)]),
                                    lw = 2, edgecolor='black')
    patches.append(tri)

coll = matplotlib.collections.PatchCollection(patches, match_original = True)
ax.add_collection(coll)

ax.set_xlim(1,12)
ax.set_ylim(0,12)

plt.show()

有谁知道我该怎么做?

标签: pythonmatplotlibcolormap

解决方案


说明似乎很好地转化为您的案例:

# values as numpy array
values = np.array([np.random.randint(0,5) for i in range(0,5)])

# define the norm 
norm = plt.Normalize(values.min(), values.max())
coll = matplotlib.collections.PatchCollection(patches, cmap='viridis',
                                              norm=norm, match_original = True)

coll.set_array(values)
polys = ax.add_collection(coll)
fig.colorbar(polys)

输出:

在此处输入图像描述


推荐阅读