Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python shapefile和matplotlib:打印shapefile坐标的多边形集合_Python_Matplotlib_Polygon_Geospatial_Shapefile - Fatal编程技术网

Python shapefile和matplotlib:打印shapefile坐标的多边形集合

Python shapefile和matplotlib:打印shapefile坐标的多边形集合,python,matplotlib,polygon,geospatial,shapefile,Python,Matplotlib,Polygon,Geospatial,Shapefile,我试图用python中的matplotlib在世界地图上绘制国家的填充多边形 我有一个形状文件,上面有每个国家的边界坐标。现在,我想用matplotlib将这些坐标(每个国家的坐标)转换为多边形。不使用底图。不幸的是,这些部分交叉或重叠。是否有工作区,可能使用点到点的距离。。或者重新排列它们? 哈! 我发现了,怎么。。我完全忽略了sf.shapes[I]。零件信息!然后归结到: # -- import -- import shapefile import matplotlib.pyplot

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

我有一个形状文件,上面有每个国家的边界坐标。现在,我想用matplotlib将这些坐标(每个国家的坐标)转换为多边形。不使用底图。不幸的是,这些部分交叉或重叠。是否有工作区,可能使用点到点的距离。。或者重新排列它们? 哈! 我发现了,怎么。。我完全忽略了sf.shapes[I]。零件信息!然后归结到:

#   -- 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')
然后它会像这样:

这里是我用来绘制多边形形状文件的另一段代码。它使用GDAL/OGR读取形状文件并正确绘制圆环形状多边形:

from osgeo import ogr
import numpy as np
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

# Extract first layer of features from shapefile using OGR
ds = ogr.Open('world_countries_boundary_file_world_2002.shp')
nlay = ds.GetLayerCount()
lyr = ds.GetLayer(0)

# Get extent and calculate buffer size
ext = lyr.GetExtent()
xoff = (ext[1]-ext[0])/50
yoff = (ext[3]-ext[2])/50

# Prepare figure
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(ext[0]-xoff,ext[1]+xoff)
ax.set_ylim(ext[2]-yoff,ext[3]+yoff)

paths = []
lyr.ResetReading()

# Read all features in layer and store as paths
for feat in lyr:
    geom = feat.geometry()
    codes = []
    all_x = []
    all_y = []
    for i in range(geom.GetGeometryCount()):
        # Read ring geometry and create path
        r = geom.GetGeometryRef(i)
        x = [r.GetX(j) for j in range(r.GetPointCount())]
        y = [r.GetY(j) for j in range(r.GetPointCount())]
        # skip boundary between individual rings
        codes += [mpath.Path.MOVETO] + \
                     (len(x)-1)*[mpath.Path.LINETO]
        all_x += x
        all_y += y
    path = mpath.Path(np.column_stack((all_x,all_y)), codes)
    paths.append(path)

# Add paths as patches to axes
for path in paths:
    patch = mpatches.PathPatch(path, \
            facecolor='blue', edgecolor='black')
    ax.add_patch(patch)

ax.set_aspect(1.0)
plt.show()
请注意,这假设多边形、多多边形可以以类似的方式处理

map(PolygonPatch, MultiPolygon(record['geometry']))
关于的答案,您应该添加以下导入:
from numpy import array
import matplotlib
并将行
cm=get\u cmap('Dark2')
替换为
cm=matplotlib.cm.get\u cmap('Dark2')


(我不太出名,不会在这篇文章中添加评论。)

你是如何制作这张照片的?我总是使用路径,就像在这个例子中:非常好。如果我运行这个脚本,我会发现它忽略了多边形中的内环,这并不总是一个问题,但需要注意的是。你在哪里定义函数
get\u cmap
?你能根据@Elendil关于
cm=matplotlib.cm.get\u cmap('Dark2')的回答修改你的答案吗
为什么
cccol
每个形状有4个值?是否可以绘制一个国家?如果是,怎么做?我理解你为什么这么做,但不应该这么做。正如你似乎理解的那样,这更适合作为一个评论。若要评论或要求作者澄清,请在他们的帖子下方留下评论-你可以随时在自己的帖子上发表评论,一旦你有足够的评论,你就可以发表评论。下次我在帖子中没有说任何错误,其他人会在日后发现错误时更正它!我只想尽我所能的帮助你,但我不能像Stack期望的那样写评论。。。多亏了你的投票,我永远都没有权利发表评论:-)
map(PolygonPatch, MultiPolygon(record['geometry']))