SciPy is an open-source library of Python that allows us to perform mathematical and scientific computations.
Spatial data refers to the data that is represented in a geometric space. SciPy gives us scipy.spatial
module, which contains tools for manipulating spatial data. The scipy.spatial
is a sub-package that can compute triangulations, Voronoi diagrams, the convex hull of a set of points using the Qhull library, KDTrees, and so on.
A convex hull is the smallest ConvexHull()
method.
Here is an example of creating a convex hull using spatial data.
#import librariesimport numpy as npimport matplotlib.pyplot as pltfrom scipy.spatial import ConvexHull#array of spatial data pointsdata_points = np.array([[1, 4],[2, 3],[3, 2],[2, 0],[4, 1],[0, 1],[5, 0],[3, 1],[1, 5],[0, 2]])#calling of ConvexHull methodhull = ConvexHull(data_points)hull_points = hull.simplices#plotting of all above data pointsplt.scatter(data_points[:,0], data_points[:,1])#visualization of a convex hullfor simplex in hull_points:plt.plot(data_points[simplex,0], data_points[simplex,1], 'r-')# plt.savefig('output/convex.png')plt.show()
Lines 2–3: We import NumPy
for working with arrays and matplotlib.pyplot
for plotting.
Line 4: We import ConvexHull
from scipy.spatial
.
Lines 7–18: We provide the array of spatial data points.
Line 20: We pass all the data points through the ConvexHull
method.
Line 24: We plot all the data points of the array by taking all the x-coordinates of data_points
as the first parameter and y-coordinates of data_points
as the second parameter in the form of a 1D array. In our case, the first array looks like [1,2,3,2,4,0,5,3,1,0] and the second array looks like [4,3,2,0,1,1,0,1,5,2].
Lines 26–29: We plot the figure’s convex hull (the red line) and save it as convex.png
.
Free Resources