What is SciPy spatial data?

SciPy is an open-source library of Python that allows us to perform mathematical and scientific computations.

Spatial data

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.

Convex hull

A convex hull is the smallest polygonIn geometry, a polygon is any closed curve made up of a set of continuous line segments (sides) without any intersections. that contains all specified points. We can create a convex hull by using the ConvexHull() method.

Example

Here is an example of creating a convex hull using spatial data.

The convex hull of given spatial data points
The convex hull of given spatial data points
#import libraries
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull
#array of spatial data points
data_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 method
hull = ConvexHull(data_points)
hull_points = hull.simplices
#plotting of all above data points
plt.scatter(data_points[:,0], data_points[:,1])
#visualization of a convex hull
for simplex in hull_points:
plt.plot(data_points[simplex,0], data_points[simplex,1], 'r-')
# plt.savefig('output/convex.png')
plt.show()

Explanation

  • 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

Copyright ©2024 Educative, Inc. All rights reserved