用热图填充多边形

2024-05-28 23:57:51 发布

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

我需要用热图填充多边形。对于多边形的来源,我使用了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>。如有任何帮助,我们将不胜感激。在


Tags: importformatplotlibasnpcmsfax
2条回答

只需将多边形设置为所需的任何颜色:

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

然后用warg match_orginal创建{}:

^{pr2}$

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

我不熟悉用于读取矢量数据/多边形的shapefile API。我通常使用OGR读取GIS矢量数据。每个多边形的颜色可以存储为每个特征的属性,也可以存储为标量,使用颜色映射指定颜色,就像您在这里所做的那样。在

相关问题 更多 >

    热门问题