从PatchCollection添加matplotlib颜色条 [英] Adding a matplotlib colorbar from a PatchCollection

查看:87
本文介绍了从PatchCollection添加matplotlib颜色条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要将Shapely MultiPolygon转换为PatchCollection,然后首先像这样为每个Polygon着色:

I'm converting a Shapely MultiPolygon to a PatchCollection, and first colouring each Polygon like so:

# ldn_mp is a MultiPolygon
cm = plt.get_cmap('RdBu')
num_colours = len(ldn_mp)

fig = plt.figure()
ax = fig.add_subplot(111)
minx, miny, maxx, maxy = ldn_mp.bounds
w, h = maxx - minx, maxy - miny
ax.set_xlim(minx - 0.2 * w, maxx + 0.2 * w)
ax.set_ylim(miny - 0.2 * h, maxy + 0.2 * h)
ax.set_aspect(1)

patches = []
for poly in ldn_mp:
    colour = cm(1. * len(filter(poly.contains, points)) / num_colours)
    patches.append(PolygonPatch(poly, fc=colour, ec='#555555', lw=0.2, alpha=1., zorder=1))
pc = PatchCollection(patches, match_original=True)
ax.add_collection(pc)
ax.set_xticks([])
ax.set_yticks([])
plt.title("Density of NO$^2$ Sensors by Borough")
plt.tight_layout()
plt.show()

但我想根据 PatchCollection 颜色为我的绘图添加一个颜色条.我不知道该怎么做;创建 pc 时如何传递 cmap 关键字?然后我该如何使用我使用的颜色调用 set_array()?

But I'd like to add a colorbar to my plot, based upon the PatchCollection colors. I'm not sure how to go about that; do I pass the cmap keyword when creating pc? How do I then call set_array() with the colours I've used?

推荐答案

我前一阵子也遇到了同样的问题.对于每个多边形,我将相应的颜色保存到名为 mycolors 的列表中:

I had the same problem a little while ago. For each polygon I saved the corresponding color to a list named mycolors:

mycolors=[]
...
mycolors.append(SSTvalue)
path_patch = patches.PathPatch(mypath, lw=1)
mypatches.append(path_patch)

我遍历了存储在Shapefile中的一系列多边形,并将每个面片存储在一个集合中.之后,我使用存储在列表中的颜色信息绘制了多边形,最终将其转换为数组,并添加了一个颜色条:

I looped over a series of multipolygons stored in a Shapefile and stored each patch in a collection. After that I plotted the polygons using the color information I had stored in the list, which was converted to an array eventually, and added a colorbar:

p = PatchCollection(mypatches, cmap=plt.get_cmap('RdYlBu_r'), alpha=1.0)
p.set_array(array(mycolors))
p.set_clim([np.ma.min(mycolors),np.ma.max(mycolors)])
plt.colorbar(p,shrink=0.5)

我过去用多边形和颜色条绘制温度值的完整脚本,该颜色和颜色条由多边形表示的世界大型海洋生态系统可以在这里找到.希望这可以帮助.干杯,特隆

The full script I used to plot temperature values with colors and a colorbar for large marine ecosystems of the world represented by polygons can be found here. Hope this helps. Cheers, Trond

这篇关于从PatchCollection添加matplotlib颜色条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆