如何用Python Matplotlib绘制不同颜色的聚类数据点?
Got it, let's fix this up for you! Visualizing nested array clusters with Matplotlib is simpler than it seems—you just need to iterate through each cluster, unpack its coordinates, and assign unique colors to each group. Here's a step-by-step implementation:
Step 1: Import Required Library
First, make sure you have Matplotlib installed (if not, run pip install matplotlib), then import it:
import matplotlib.pyplot as plt
Step 2: Define Your Clustered Data
Paste your nested array data directly into your script:
# Your original clustered data clusters = [ [(1, 3), (2, 5), (2, 6), (1, 2), (1, 8)], [(4, 7), (5, 5), (6, 4)], [(8, 9), (10, 9), (11, 12), (10, 12)], [(18, 20), (20, 29), (17, 16), (18, 22)] ]
Step 3: Plot Each Cluster with Unique Colors
We’ll loop through each cluster, extract its x/y coordinates, and plot them with a distinct color. We’ll also add a legend so you can easily identify each cluster:
# Set up the figure size for better visibility plt.figure(figsize=(10, 8)) # Use a list of distinct colors (customize these to your preference!) colors = ['#ff4444', '#0099cc', '#4CAF50', '#ff9800'] # Iterate over clusters and their matching colors for cluster_num, (cluster, color) in enumerate(zip(clusters, colors), start=1): # Unpack x and y coordinates from the cluster's points x_vals = [point[0] for point in cluster] y_vals = [point[1] for point in cluster] # Plot the points with a label for the legend plt.scatter(x_vals, y_vals, color=color, label=f'Cluster {cluster_num}', s=120, alpha=0.8) # Add labels and a title to make the plot readable plt.xlabel('X Coordinate', fontsize=12) plt.ylabel('Y Coordinate', fontsize=12) plt.title('Clustered Data Visualization', fontsize=14, pad=20) # Show the legend to distinguish clusters plt.legend(fontsize=10) # Display the final plot plt.show()
Key Notes to Clear Up Confusion:
- Unpacking Coordinates: The list comprehensions
x_vals = [point[0] for point in cluster]andy_vals = [point[1] for point in cluster]split each (x,y) tuple into separate lists—this is what Matplotlib needs to plot points. - Color Flexibility: If you have more clusters than 4, use a colormap instead of hardcoding colors. For example:
colors = plt.cm.tab10(range(len(clusters))) # Uses a built-in color map with 10 distinct colors - Customization: Adjust
s(point size) andalpha(transparency) to make overlapping points easier to see, or tweak thefigsizeto fit your needs.
This code will generate a scatter plot where each cluster is a unique color, with a legend to map colors to cluster numbers—exactly what you’re looking for!
内容的提问来源于stack exchange,提问作者sedrick

