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

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) and np (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 labels array uses values 1 and -1, but your code is checking for labels[:]==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, your classes array 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?

  1. Added Imports: The import statements ensure Python recognizes the matplotlib.pyplot and numpy modules you're using.
  2. Fixed Label Filtering: Swapped labels[:]==0 for labels == -1 to target the negative class in your dataset. Now both green triangles (class 1) and red squares (class -1) will appear on the plot.
  3. Aligned Classes with Labels: Updated the classes array to match your actual label values so the legend displays correctly. If you intended classes to represent a mapping (e.g., -1 → 0, 1 → 1), you could adjust the legend line to plt.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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 18:57:27