python-scipyHow can I use Python and SciPy to generate a Voronoi diagram?
To generate a Voronoi diagram with Python and SciPy, you can use the scipy.spatial.Voronoi
class. This class takes a list of coordinates as input and returns a collection of vertices and regions.
Below is an example of code that generates a Voronoi diagram with 10 randomly generated points:
import numpy as np
from scipy.spatial import Voronoi
# Generate 10 random points
points = np.random.rand(10,2)
# Create a Voronoi object
vor = Voronoi(points)
# Plot the diagram
import matplotlib.pyplot as plt
plt.plot(points[:,0], points[:,1], 'b.')
plt.plot(vor.vertices[:,0], vor.vertices[:,1], 'g-')
for simplex in vor.ridge_vertices:
simplex = np.asarray(simplex)
plt.plot(vor.vertices[simplex,0], vor.vertices[simplex,1], 'k-')
plt.show()
This code will generate an output like this:
The code is composed of the following parts:
import numpy as np
andfrom scipy.spatial import Voronoi
: imports the necessary modules for generating the Voronoi diagram.points = np.random.rand(10,2)
: generates 10 random points.vor = Voronoi(points)
: creates a Voronoi object using theVoronoi
class.plt.plot(points[:,0], points[:,1], 'b.')
: plots the points.plt.plot(vor.vertices[:,0], vor.vertices[:,1], 'g-')
: plots the vertices of the Voronoi diagram.for simplex in vor.ridge_vertices:
: iterates over the ridge vertices of the Voronoi diagram.plt.plot(vor.vertices[simplex,0], vor.vertices[simplex,1], 'k-')
: plots the ridge vertices.plt.show()
: displays the plot.
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How can I use Python and SciPy to find the zeros of a function?
- How can I use Python and Numpy to zip files?
- How do I create a numpy array of zeros using Python?
- How can I use Python Scipy to zoom in on an image?
- How can I use Python and Numpy to parse XML data?
- How can I use Python and SciPy to implement an ARIMA model?
- How can I use Python Scipy to solve a Poisson equation?
- How do I create a numpy array of zeros using Python?
- How do I use Python Scipy to perform a Z test?
See more codes...