python - 将 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()
有谁知道我该怎么做?
解决方案
该说明似乎很好地转化为您的案例:
# 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)
输出:
推荐阅读
- zsh - 如何发送时间信息以在 zsh-theme 中运行?
- laravel - 为什么 Laravel 的actingAs 没有按预期工作?
- ios - 使用 viewDidAppear() 在 swift5 中关闭另一个 ViewController 后刷新 ViewController
- android - 在 ViewModel 中添加用例时未解析的引用 DaggerApplicationComponent
- python - 如何在 3d 中获得边界(一组点)的平均曲线(一组点)?
- css - 总是在最后一个位置订购弹性项目
- spring - 为什么spring会覆盖标头中的Content-Type?
- python - 如何只替换之后有一些字符的 \n
- sql - 使用 PIVOT 将行转换为列
- javascript - 如何在单独的页面中呈现反应组件?