[英]Set cmap to a Matplotlib PatchCollection
I have a Patch Collection conformed by several polygons (triangles).我有一个由多个多边形(三角形)组成的补丁集。 Each of that triangle have associated an integer value .
每个三角形都关联了一个整数值。 I would like to set a color map to that Patch Collection based on the different values of the triangles.
我想根据三角形的不同值为该补丁集合设置颜色映射。
This is my code:这是我的代码:
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()
Does anyone know how could I do this?有谁知道我怎么能做到这一点?
This instruction seems to translate to your case pretty well:此说明似乎很好地转化为您的案例:
# 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)
Output:输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.