【问题标题】:Filling shapefile polygons with a color in matplotlib在 matplotlib 中用颜色填充 shapefile 多边形
【发布时间】:2018-01-30 11:32:35
【问题描述】:

我正在寻找基于值填充 shapefile 多边形的方法。 到目前为止,从底图教程 (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 的值相关的颜色。

提前致谢

【问题讨论】:

标签: python matplotlib shapefile matplotlib-basemap


【解决方案1】:

您似乎想在底图中生成等值线图。
为此,您需要一个颜色映射cmap 和一个标准化norm 以便将值映射到颜色cmap(norm(val))。对于每个形状,可以将Polygon 的颜色设置为字典中的相应颜色,在本例中为cmap(norm(dict1[info['ID_2']]))

PatchCollection 内部,match_original=True 需要设置为保留原始多边形的颜色。

最后,从颜色图和规范化生成颜色图可能很有用。

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    相关资源
    最近更新 更多