创建colorbar并设置Polygon Patch Collection Matplotlib的edgecolor

2024-10-03 15:23:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有许多多边形坐标,每个多边形区域都有一个分数值。我试图通过一个类似热图的二维图来可视化这些多边形及其相关的分数。我的代码可以绘制这样的内容,但是,我很难根据为PatchCollection设置的颜色来显示colormap。另外,我为多边形对象指定了一个edgecolor,但是它没有显示出来。我用来绘图的数据附在here。在

import shapely
import pickle as pkl 
tiles = pkl.load(open("polygons.pkl",'r'))
area_lst=[]
for tile in tiles:
    area_lst.append(shapely.geometry.Polygon(tile).area)
sorted_ascend_tile_by_size= list(np.array(tiles)[np.argsort(area_lst)[::-1]])
gammas=np.random.random(len(tiles))
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon

fig,ax = plt.subplots(1)
patches = []
cmap = plt.get_cmap('cool')
colors = cmap(gammas)

for tile_idx in range(len(tiles)):
    polygon = Polygon(sorted_ascend_tile_by_size[tile_idx],closed=True,alpha=0.8,linewidth=1,edgecolor='black',fill=False,zorder=1)
    patches.append(polygon)

collection = PatchCollection(patches)
pcollection = ax.add_collection(collection)
collection.set_color(colors)

ax.autoscale_view()

这是代码输出的图:

enter image description here

我尝试过使用ScalarMappable对象添加colorbar,但是我得到错误TypeError: You must first set_array for mappable

^{pr2}$

Tags: importfornpareaax多边形collectioncmap
1条回答
网友
1楼 · 发布于 2024-10-03 15:23:17

虽然听起来很有趣,但错误消息实际上已经告诉了您解决方案。只需使用set_array方法将数组设置为ScalarMappable。数组可以为空。在

import matplotlib.pyplot as plt
sm = plt.cm.ScalarMappable(cmap="jet", norm=plt.Normalize(vmin=0, vmax=1))
sm.set_array([])
plt.colorbar(sm)
plt.show()

相关问题 更多 >