是什么导致了这个 NameError: name 'ax' is not defined in my Python code?

use*_*812 3 python numpy matplotlib

所以我想用这个代码构建一个折线图:

x_data = df['Product Type']
y_data = df['Total Amount']

def lineplot(x_data, y_data, x_label="Product Type", y_label="Total Amount", title="Sales"):
    __, ax = plt.subplots()

    ax.plot(x_data, y_data, lw=3, color ='#539caf', alpha =1)

ax.set_title(title)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
Run Code Online (Sandbox Code Playgroud)

但它只会产生此错误消息: NameError: name 'ax' is not defined

任何人都可以告诉我是什么导致了这个问题?我尝试使用其他方法,但ax.plot在 Python 中的数据可视化中这似乎很常见,所以我认为我需要正确地做到这一点。谢谢!

Jmo*_*sky 5

您需要修复最后 3 行的缩进,然后单独调用该函数。

x_data = df['Product Type']
y_data = df['Total Amount']

def lineplot(x_data, y_data, x_label="Product Type", y_label="Total Amount", title="Sales"):
    __, ax = plt.subplots()

    ax.plot(x_data, y_data, lw=3, color ='#539caf', alpha =1)

    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

lineplot(x_data, y_data)
Run Code Online (Sandbox Code Playgroud)