shapefile和matplotlib:绘制shapefile坐标的多边形集合 [英] shapefile and matplotlib: plot polygon collection of shapefile coordinates

查看:157
本文介绍了shapefile和matplotlib:绘制shapefile坐标的多边形集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python中的matplotlib在世界地图上绘制国家的填充多边形.

I'm trying to plot filled polygons of countries on the world map with matplotlib in python.

我有一个shapefile,其中包含每个国家/地区的国家边界坐标.现在,我想将这些坐标(针对每个国家)转换为带有matplotlib的多边形.不使用底图.不幸的是,这些部分是交叉或重叠的.有没有动工,也许是使用点到点的距离.或者重新排序?

I've got a shapefile with country boundary coordinates of every country. Now, I want to convert these coordinates (for each country) into a polygon with matplotlib. Without using Basemap. Unfortunately, the parts are crossing or overlapping. Is there a workarund, maybe using the distance from point to point.. or reordering them ?

推荐答案

哈! 我发现了,如何..我完全忽略了sf.shapes [i] .parts信息!然后归结为:

Ha! I found out, how.. I completely neglected, the sf.shapes[i].parts information! Then it comes down to:

#   -- import --
import shapefile
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
#   -- input --
sf = shapefile.Reader("./shapefiles/world_countries_boundary_file_world_2002")
recs    = sf.records()
shapes  = sf.shapes()
Nshp    = len(shapes)
cns     = []
for nshp in xrange(Nshp):
    cns.append(recs[nshp][1])
cns = array(cns)
cm    = get_cmap('Dark2')
cccol = cm(1.*arange(Nshp)/Nshp)
#   -- plot --
fig     = plt.figure()
ax      = fig.add_subplot(111)
for nshp in xrange(Nshp):
    ptchs   = []
    pts     = array(shapes[nshp].points)
    prt     = shapes[nshp].parts
    par     = list(prt) + [pts.shape[0]]
    for pij in xrange(len(prt)):
     ptchs.append(Polygon(pts[par[pij]:par[pij+1]]))
    ax.add_collection(PatchCollection(ptchs,facecolor=cccol[nshp,:],edgecolor='k', linewidths=.1))
ax.set_xlim(-180,+180)
ax.set_ylim(-90,90)
fig.savefig('test.png')

然后它将如下所示:

Then it will look like this:

这篇关于shapefile和matplotlib:绘制shapefile坐标的多边形集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆