[英]Filling shapefile polygons with a color in matplotlib
我正在尋找一種基於值填充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的值相關的顏色。
提前致謝
似乎您想在底圖中生成一個Choropleth圖。
為此,您需要一個色圖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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.