python - 通过热图填充多边形

标签 python matplotlib heatmap shapefile

我需要使用热图填充我的多边形。对于多边形的来源,我使用 shapefile 。 这是我的代码:

import shapefile
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.cm as mcm
import matplotlib.image as mpimg 
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import pylab as plb   


fig     = plt.figure()
ax      = fig.add_subplot(111)
ax.set_frame_on(False)

sf = shapefile.Reader("./data/boundary-polygon")
recs    = sf.records()
shapes  = sf.shapes()
print shapes[1].__dict__
Nshp    = len(shapes)
cns     = []
for nshp in xrange(Nshp):
    cns.append(recs[nshp][1])
cns = np.array(cns)
cm    = mcm.get_cmap('Dark2')
cccol = cm(1.*np.arange(Nshp)/Nshp)
#   facecolor=cccol[nshp,:],

for nshp in xrange(Nshp):
    ptchs   = []
    pts     = np.array(shapes[nshp].points)
    prt     = shapes[nshp].parts
    par     = list(prt) + [pts.shape[0]]
    for pij in xrange(len(prt)):
        ptchs.append(Polygon(pts[par[pij]:par[pij+1]], alpha=1))
    ax.add_collection(PatchCollection(ptchs,facecolors=((1, 1, 1, 1),),alpha=0.1 ,linewidths=1))
ax.set_xlim(54,67)
ax.set_ylim(50,57)

我要改facecolors=((1, 1, 1, 1),)facecolors=<image_of_my_heat_map> 。任何有关此问题的帮助将不胜感激。

最佳答案

只需将多边形设置为您想要的任何颜色:

ptchs=[]
for pij in xrange(len(prt)):
    ptchs.append(Polygon(pts[par[pij]:par[pij+1]], alpha=1, color=your_color))

然后使用 Warg match_orginal 创建 PatchCollection:

ax.add_collection(PatchCollection(ptchs, match_orginal=True, alpha=0.1 ,linewidths=1))

另请参阅Why is matplotlib.PatchCollection messing with color of the patches?

关于python - 通过热图填充多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18951558/

相关文章:

matplotlib - 如何在 matplotlib 中的不透明表面上绘制图形?

r - 为什么R的热图不能始终如一地作用于颜色单元?

python - Paramiko/Netmiko SSH 错误 - 'Channel' 对象没有属性 'update_environment_variables'

python - 在不知道键的情况下查找字典值的类型

python - 如何在所有条形图子图上显示 x 轴标签?

python - Pandas : using both log and stack on a bar plot

python - 快速概览 OOP php 到 python?

python - 如何删除列表列表中的部分重复项

seaborn - 如何删除 seaborn 热图中的颜色条?

python - matplotlib/seaborn 热图使用带有日期时间索引的 pandas 数据框