import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi, voronoi_plot_2d
np.random.seed(42)
num_points = 15
points = np.random.rand(num_points, 2)
vor = Voronoi(points)
fig, ax = plt.subplots(figsize=(8, 6))
voronoi_plot_2d(vor, ax=ax, show_vertices=False, line_colors="blue", line_width=1.5)
ax.scatter(points[:, 0], points[:, 1], color="red", marker="o", label="Original Points")
plt.title("Voronoi Diagram")
plt.xlabel("X")
plt.ylabel("Y")
plt.legend()
plt.grid()
plt.show()
#source code --> clcoding.com
Code Explanation:
Import Required Libraries
import
numpy as np
import
matplotlib.pyplot as plt
from
scipy.spatial import Voronoi, voronoi_plot_2d
numpy
→ Used to generate random points.
matplotlib.pyplot
→ Used to plot the Voronoi diagram.
scipy.spatial.Voronoi
→ Computes the Voronoi diagram.
scipy.spatial.voronoi_plot_2d
→ Helps in visualizing the Voronoi structure.
np.random.seed(42) # Set seed for reproducibility
num_points
= 15 # Number of random points
points
= np.random.rand(num_points, 2) #
Generate 15 random points in 2D (x, y)
np.random.seed(42)
→ Ensures that the random points are the same every time the code runs.
num_points
= 15 → Defines 15 points for the Voronoi diagram.
np.random.rand(num_points, 2) → Generates 15 random points with x and y coordinates between [0,1].
Compute Voronoi Diagram
vor
= Voronoi(points)
Computes
the Voronoi diagram based on the input points.
The
Voronoi diagram partitions the space so that each region contains all locations
closest to one given point.
Create the Plot
fig,
ax = plt.subplots(figsize=(8, 6))
Creates
a figure (fig) and an axis (ax) for plotting.
figsize=(8,6) sets the figure size to 8 inches wide and 6 inches tall.
Plot the Voronoi Diagram
voronoi_plot_2d(vor,
ax=ax, show_vertices=False, line_colors="blue", line_width=1.5)
voronoi_plot_2d(vor,
ax=ax) → Plots the Voronoi diagram on the given axis.
show_vertices=False
→ Hides the Voronoi vertices (points where the regions meet).
line_colors="blue"
→ Sets the region boundaries to blue.
line_width=1.5
→ Makes the region boundaries thicker for better visibility.
Plot the Original Points
ax.scatter(points[:,
0], points[:, 1], color="red", marker="o",
label="Original Points")
Plots
the original 15 random points using red circular markers (o).
points[:,
0] → Extracts the x-coordinates of the points.
points[:,
1] → Extracts the y-coordinates of the points.
label="Original
Points" → Adds a legend entry for the points.
plt.title("Voronoi
Diagram") # Set title
plt.xlabel("X") # X-axis label
plt.ylabel("Y") # Y-axis label
plt.legend() # Show legend
plt.grid() # Add grid lines
Adds
a title, axis labels, a legend, and grid lines for clarity.
plt.show()
Displays
the final Voronoi diagram.
0 Comments:
Post a Comment