受 pelson 回答的启发,我发布了我的解决方案。我会留给你最有效的方法,所以我暂时不会接受任何答案。
#! /usr/bin/env python
import sys
import os
from pylab import *
from mpl_toolkits.basemap import Basemap
import matplotlib as mp
from shapelib import ShapeFile
import dbflib
from matplotlib.collections import LineCollection
from matplotlib import cm
def get_shapeData(shp,dbf):
for npoly in range(shp.info()[0]):
shpsegs = []
shpinfo = []
shp_object = shp.read_object(npoly)
verts = shp_object.vertices()
rings = len(verts)
for ring in range(rings):
if ring == 0:
shapedict = dbf.read_record(npoly)
name = shapedict["name_long"]
continent = shapedict["continent"]
lons, lats = zip(*verts[ring])
if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91:
raise ValueError,msg
x, y = m(lons, lats)
shpsegs.append(zip(x,y))
shapedict['RINGNUM'] = ring+1
shapedict['SHAPENUM'] = npoly+1
shpinfo.append(shapedict)
lines = LineCollection(shpsegs,antialiaseds=(1,))
lines.set_facecolors(cm.jet(np.random.rand(1)))
lines.set_edgecolors('k')
lines.set_linewidth(0.3)
ax.add_collection(lines)
if __name__=='__main__':
f=figure(figsize=(10,10))
ax = plt.subplot(111)
m = Basemap(projection='merc',llcrnrlat=30,urcrnrlat=72,\
llcrnrlon=-40,urcrnrlon=50,resolution='c')
m.drawcountries(linewidth=0.1,color='w')
sfile = 'ne_10m_admin_0_countries'
shp = ShapeFile(sfile)
dbf = dbflib.open(sfile)
get_shapeData(shp,dbf)
show()
sys.exit(0)
这是结果
这是我的示例,如何以正确的颜色填写阿尔巴尼亚(我知道不是很优雅;))。
#HACK for Albania
shpsegs = []
shpinfo = []
shp_object = shp.read_object(9)
verts = shp_object.vertices()
rings = len(verts)
for ring in range(rings):
if ring == 0:
shapedict = dbf.read_record(9)
name = shapedict["name_long"]
continent = shapedict["continent"]
lons, lats = zip(*verts[ring])
if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91:
raise ValueError,msg
x, y = m(lons, lats)
shpsegs.append(zip(x,y))
shapedict['RINGNUM'] = ring+1
shapedict['SHAPENUM'] = npoly+1
shpinfo.append(shapedict)
lines = LineCollection(shpsegs,antialiaseds=(1,))
if name == 'Albania':
lines.set_facecolors('w')
lines.set_edgecolors('k')
lines.set_linewidth(0.3)
ax.add_collection(lines)
在完成所有其他形状后执行此操作很重要。也许你可以去掉这段代码的某些部分,但正如我所说,这对我来说已经足够了。
对于我的应用程序,我按名称或大洲为国家着色,因此这些行:
name = shapedict["name_long"]
continent = shapedict["continent"]
我从这个网站得到的数据:http://www.naturalearthdata.com/