You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于PyGAD的遗传算法聚类结果绘图图例创建求助

Fixing Legend for GA-Based Clustering Plot

Hey there! Let's get that legend working properly for your PyGAD clustering plot. The main idea is to assign clear labels to your scatter plots (both cluster data points and centers) so Matplotlib knows exactly what to show in the legend. Here are two straightforward approaches depending on how you want your legend to look:

Approach 1: Per-Cluster Data + Center Labels

This keeps your legend aligned with your manual clustering setup, with separate entries for each cluster's data points and its corresponding center:

import matplotlib.pyplot as plt

for cluster_idx in range(num_clusters):
    cluster_x = data[clusters[cluster_idx], 0]
    cluster_y = data[clusters[cluster_idx], 1]
    
    # Plot cluster data points with a clear label
    data_scatter = plt.scatter(cluster_x, cluster_y, label=f"Cluster {cluster_idx}")
    
    # Plot the cluster center, matching the data's color and adding a center-specific label
    center_x, center_y = cluster_centers[cluster_idx]
    plt.scatter(center_x, center_y, 
                marker="s", s=100, 
                label=f"Cluster {cluster_idx} Center",
                color=data_scatter.get_facecolor()[0])  # Reuse data point color for consistency

plt.title("Clustering using PyGAD")
# Move legend outside the plot to avoid blocking data
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.show()

Key Details:

  • We use the label parameter in each scatter() call to define what shows up in the legend
  • The cluster center uses the same color as its corresponding data points (via data_scatter.get_facecolor()[0]) for visual consistency
  • bbox_to_anchor shifts the legend to the side, which is helpful if your clusters take up most of the plot area

Approach 2: Unified Center Label (Cleaner for Many Clusters)

If you have lots of clusters and don't want a duplicate center entry for each one, you can create a custom legend that shows cluster labels once plus a single entry for cluster centers:

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

# Initialize a list to hold cluster data handles
cluster_handles = []
# Create a custom handle for cluster centers
center_handle = Line2D(
    [], [], marker='s', color='black', linestyle='', 
    markersize=10, label='Cluster Center'
)

for cluster_idx in range(num_clusters):
    cluster_x = data[clusters[cluster_idx], 0]
    cluster_y = data[clusters[cluster_idx], 1]
    
    # Plot cluster data and save the scatter handle
    scatter = plt.scatter(cluster_x, cluster_y, label=f"Cluster {cluster_idx}")
    cluster_handles.append(scatter)
    
    # Plot center without a label (we'll add it via the custom handle)
    center_x, center_y = cluster_centers[cluster_idx]
    plt.scatter(center_x, center_y, 
                marker="s", s=100, 
                color=scatter.get_facecolor()[0])

# Combine cluster handles and the center handle for the legend
all_handles = cluster_handles + [center_handle]

plt.title("Clustering using PyGAD")
plt.legend(handles=all_handles, bbox_to_anchor=(1.05, 1), loc='upper left')
plt.show()

Key Details:

  • We use Line2D to create a custom legend entry for cluster centers (since we don't want to repeat it for every cluster)
  • Only the cluster data points get individual labels, and we manually combine all handles for the final legend

Either approach will give you a clear, functional legend just like your manual clustering plot. Pick the one that fits your visualization needs best!

内容的提问来源于stack exchange,提问作者Faza Adhzima

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 14:12:33