使用Python的matplotlib/basemap上色状态
我想生成一张美国地图,并给每个州涂上不同的颜色。请问有没有办法用Python的basemap来实现这个?
1 个回答
25
在GitHub的Basemap库里,有一个格式很好的例子:fillstates.py。这个例子里用到的地图文件(dbf | shp | shx)也包含在示例文件夹里。
下面是这个例子的简化版本:
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
# create the map
map = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
# load the shapefile, use the name 'states'
map.readshapefile('st99_d00', name='states', drawbounds=True)
# collect the state names from the shapefile attributes so we can
# look up the shape obect for a state by it's name
state_names = []
for shape_dict in map.states_info:
state_names.append(shape_dict['NAME'])
ax = plt.gca() # get current axes instance
# get Texas and draw the filled polygon
seg = map.states[state_names.index('Texas')]
poly = Polygon(seg, facecolor='red',edgecolor='red')
ax.add_patch(poly)
plt.show()
结果图,德克萨斯州被填充为红色:
需要注意的是,当我们加载一个地图文件时,形状和属性会分别存储在map.states
和map.states_info
中,这些都是基于readshapefile
调用时使用的name
参数的列表。所以,要查找某个特定州的形状,我们需要根据属性构建一个对应的州名列表。