How to plot features in a shapefile in Python

1   How to plot points

from osgeo import ogr
from matplotlib import pyplot as plt

file = ogr.Open("p:/courses/python/points.shp")
lyr = file.GetLayer(0)
x = []
y = []
for i in range(lyr.GetFeatureCount()):
    feat = lyr.GetFeature(i)
    geom = feat.geometry()
    pnt = geom.GetPoint()
    x.append(pnt[0])
    y.append(pnt[1])

for i in range(1, len(x)):
    plt.plot([x[0], x[i]], [y[0], y[i]])

plt.show()

points-plot.png

2   Homework: Write the find_nearest function

Write a Python function that returns the index of the neighbor feature that is closest to the first feature at index 0. Use the same exercise data “Points.shp.”