How to plot points in a shapefile in Python
Institute for Environmental and Spatial Analysis...University of North Georgia
1 Introduction
We want to plot all the points in Points.zip using matplotlib.
2 Python code
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()
3 Homework: Write the find_nearest function
Write a Python function called find_nearest
that returns the index of the neighbor feature that is closest to the first feature at index 0. This function should
- take one argument
shp_path
, which is equivalent to"p:/courses/python/points.shp"
in the exercise, - open this shapefile at
shp_path
, - read all the features,
- calculate distances,
- find the nearest feature from the first feature, and
- return its index.
Use the same Points.shp from the exercise above. Please submit your function in FirstLastname_find_nearest.py
.