在matplotlib中填充shapefile多边形颜色

5

我正在寻找一种基于数值填充shapefile多边形的方法。 到目前为止,从basemap教程(http://basemaptutorial.readthedocs.io/en/latest/shapefile.html)中,我已经找到了如何使用特定颜色填充多边形的方法。

import matplotlib.pyplot as plt
import pypyodbc
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
from matplotlib.patches import PathPatch
import numpy as np
 
fig= plt.figure()
ax= fig.add_subplot(111)
m=Basemap(projection='cyl',llcrnrlat=34.5,llcrnrlon=19,urcrnrlat=42,urcrnrlon=28.5,resolution='h')
m.drawmapboundary(fill_color='aqua')
m.fillcontinents(color='#ddaa66',lake_color='aqua')
m.drawcoastlines()
m.readshapefile('nomoi','nomoi')

patches   = []

for info, shape in zip(m.nomoi_info, m.nomoi):
    if info['ID_2'] == 14426:
        patches.append( Polygon(np.array(shape), True) )

ax.add_collection(PatchCollection(patches, facecolor='m', edgecolor='k', linewidths=1., zorder=2))

plt.show()

我可以帮助你进行翻译。以下是对该段内容的翻译:

我想做的是从一个字典中获取值,例如:

dict1={14464: 1.16, 14465: 1.35, 14466: 1.28, 14467: 1.69, 14468: 1.81, 14418: 1.38}

其中,键是来自上面代码中的shapefile的info ['ID_2']列,值是我想要表示颜色的变量。这意味着具有从1.16到1.81变化的颜色映射,并且每个多边形(ID_2)都有与其值相关的颜色来自dict1。

提前致谢


我从哪里获取nomoi shapefile? - ImportanceOfBeingErnest
我不知道在哪里上传它,希望这个链接有效 https://drive.google.com/open?id=1Q47l1uSomLyDrHG2mxMiK3solsmWwcOd - Ignatios Chatzidiamantis
1个回答

7
看起来你想在basemap中生成区域分布图。
为此,您需要一个colormap(cmap)和一个归一化(norm),以便将值映射到颜色,cmap(norm(val))。对于每个形状,可以将多边形的颜色设置为字典中相应的颜色,即cmap(norm(dict1[info['ID_2']]))。
在PatchCollection内部,需要设置match_original=True以保留原始多边形的颜色。
最后,从colormap和归一化生成colormap可能是有用的。
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import numpy as np

fig= plt.figure()
ax= fig.add_subplot(111)
m=Basemap(projection='cyl',llcrnrlat=34.5,llcrnrlon=19,
                           urcrnrlat=42,urcrnrlon=28.5,resolution='h')
m.drawmapboundary(fill_color='aqua')
m.fillcontinents(color='w',lake_color='aqua')
m.drawcoastlines()
m.readshapefile('data/nomoi/nomoi','nomoi')

dict1={14464: 1.16, 14465: 1.35, 14466: 1.28, 14467: 1.69, 14468: 1.81, 14418: 1.38}
colvals = dict1.values()

cmap=plt.cm.RdYlBu
norm=plt.Normalize(min(colvals),max(colvals))

patches   = []

for info, shape in zip(m.nomoi_info, m.nomoi):
    if info['ID_2'] in list(dict1.keys()):
        color=cmap(norm(dict1[info['ID_2']]))
        patches.append( Polygon(np.array(shape), True, color=color) )

pc = PatchCollection(patches, match_original=True, edgecolor='k', linewidths=1., zorder=2)
ax.add_collection(pc)

#colorbar
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array(colvals)
fig.colorbar(sm, ax=ax)

plt.show()

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接