Python matplotlib点绘图问题求助
Fixing Your Matplotlib Scatter Plot Issue
Hey there! Let's get your plot working properly. I noticed a couple of key issues in your code that are preventing the plot from showing up as expected:
Key Problems Identified
- Missing Required Imports: You're using
plt(from matplotlib) andnp(from numpy) but haven't included the import statements at the top of your code. This is likely causing silent failures that stop the plot from rendering. - Mismatched Label Filtering: Your
labelsarray uses values1and-1, but your code is checking forlabels[:]==0—there are no 0s in your labels! This means the second dataset (red squares) has no points to plot, which breaks the plot rendering. Additionally, yourclassesarray doesn't align with your actual label values, making the legend incorrect.
Corrected Code
# Add the necessary imports first import matplotlib.pyplot as plt import numpy as np def graph(features, labels, classes): # Filter using the actual label values present: 1 and -1 plt.plot(features[labels == 1, 0], features[labels == 1, 1], 'g^', features[labels == -1, 0], features[labels == -1, 1], 'rs') plt.axis([-4, 4, -4, 4]) plt.xlabel('x: feature 1') plt.ylabel('y: feature 2') # Update legend to match your actual class labels plt.legend([f'Class {classes[1]}', f'Class {classes[0]}']) plt.show() # Your original data features = np.array([[1,1], [1,0], [0,1], [-1,-1], [0.5,3], [0.7,2], [-1,0], [-1,1], [2,0], [-2,-1]]) labels = np.array([1,1,-1,-1,1,1,-1,-1,1,-1]) # Adjust classes to match your actual label values classes = [-1, 1] # Call the function to generate the plot graph(features, labels, classes)
What Changed?
- Added Imports: The
importstatements ensure Python recognizes thematplotlib.pyplotandnumpymodules you're using. - Fixed Label Filtering: Swapped
labels[:]==0forlabels == -1to target the negative class in your dataset. Now both green triangles (class 1) and red squares (class -1) will appear on the plot. - Aligned Classes with Labels: Updated the
classesarray to match your actual label values so the legend displays correctly. If you intendedclassesto represent a mapping (e.g.,-1→0,1→1), you could adjust the legend line toplt.legend(['Class 1', 'Class 0'])instead.
Run this corrected code, and you should see a properly rendered scatter plot with all your points plotted in the correct colors and a matching legend!
内容的提问来源于stack exchange,提问作者lxx2015
相关产品推荐
相关产品推荐

