help pls How i can color the unfilled (white) regions in the corresponding color points, just like all the others? the code accepts several clusters as input, gives each a light and builds a corresponding Voronoi diagram, marking in bold the boundaries between different clusters
the code accepts several clusters as input, gives each a light and builds a corresponding Voronoi diagram, marking in bold the boundaries between different clusters
from scipy.spatial import Voronoi, voronoi_plot_2d
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
np.random.seed(10001100)
n = 5 # Number of series
num_points_per_series = 10
cluster_distance = 1.0
all_points = []
points_clustering = []
for i in range(n):
cluster_center = np.random.randn(2) * cluster_distance
points = cluster_center + np.random.randn(num_points_per_series, 2) * 0.5 # Adding randomness within each cluster
all_points.extend(points)
points_clustering.extend([i] * num_points_per_series) # Track the cluster of each point
# Compute Voronoi diagram for all points
vor = Voronoi(np.array(all_points))
# Function to get point color by cluster
def get_point_color(cluster_index, n_clusters):
# Generate a colormap for n_clusters discrete colors:
cmap = plt.get_cmap('viridis')
colors = cmap(np.linspace(0, 1, n_clusters))
discrete_cmap = ListedColormap(colors)
# Now, use the cluster_index to get the color from the discrete colormap
return discrete_cmap.colors[cluster_index]
def plot_filled_voronoi_with_boundaries2(vor, points_clustering, n_clusters):
fig, ax = plt.subplots()
# Generate colormap for n_clusters discrete colors
cmap = ListedColormap(plt.cm.viridis(np.linspace(0, 1, n_clusters)))
# Plot Voronoi diagram boundaries and filled regions
voronoi_plot_2d(vor, ax=ax, show_vertices=False, line_colors='black', line_width=0.5)
# Fill Voronoi regions and thicken boundary lines between different clusters
for point_idx, region in enumerate(vor.point_region):
polygons = vor.regions[region]
if all(v >= 0 for v in polygons): # Check the region vertices are valid (not -1, which indicates an open region)
polygon = [vor.vertices[i] for i in polygons]
region_color = get_point_color(points_clustering[point_idx], n_clusters)
plt.fill(*zip(*polygon), alpha=0.5, color=region_color)
for ridge_points, ridge_vertices in zip(vor.ridge_points, vor.ridge_vertices):
if all(v != -1 for v in ridge_vertices):
v1, v2 = ridge_vertices
p1, p2 = ridge_points
if points_clustering[p1] != points_clustering[p2]:
plt.plot(vor.vertices[[v1, v2], 0], vor.vertices[[v1, v2], 1], 'k-', linewidth=2)
# Mark the original points
for point_idx, point in enumerate(vor.points):
plt.scatter(point[0], point[1], color=get_point_color(points_clustering[point_idx], n_clusters), edgecolor='black', zorder=2)
plt.show()
# Call function with vor, points_clustering and n
plot_filled_voronoi_with_boundaries2(vor, points_clustering, n)
im looking into code... try replace all(v>=0) to any or True