viewing a polygon read from shapefile with matplotlib

99封情书 提交于 2020-01-06 19:46:10

问题


I am trying to view a basic polygon read from a Shapefile using matplotlib and pyshp But all my efforts yield just an empty axes with no polygon. Here are few of my tries, using the dataset showing the borders of Belgium:

import shapefile as sf
r = sf.Reader("BEL_adm/BEL_adm0")
p=r.shapes()
b=p[0]
points = b.points

import matplotlib.pyplot as plt
from matplotlib.path import Path
imporst matplotlib.patches as patches

verts = points

verts = []
for x,y in points:
    verts.append(tuple([x,y]))

codes = ['']*len(verts)
codes[0] = Path.MOVETO
codes[-1] = Path.CLOSEPOLY

for i in range(1,len(verts)):
    codes[i]=Path.LINETO

path = Path(verts, codes)
fig = plt.figure()
ax = fig.add_subplot(111)
patch = patches.PathPatch(path, facecolor='orange', lw=2)
ax.add_patch(patch)
ax.set_xlim(-2,2)
ax.set_ylim(-2,2)
plt.show()

Another try with patches also yields an empty frame:

fig = plt.figure(figsize=(11.7,8.3))

ax = plt.subplot(111)
x,y=zip(*b.points)
import matplotlib.patches as patches
import matplotlib.pyplot as plt
bol=patches.Polygon(b.points,True, transform=ax.transAxes)

ax.add_patch(bol)
ax.set_ylim(0,60)
ax.set_xlim(0,200)
plt.show()

Would be happy to see what I am missing.
Thanks, Oz


回答1:


instead of calling set_xlim(), set_ylim() to set the range of axis, you can use ax.autoscale().

For your Polygon version, you don't need to set transform argument to ax.transAxes, just call:

bol=patches.Polygon(b.points,True)


来源:https://stackoverflow.com/questions/10871085/viewing-a-polygon-read-from-shapefile-with-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!