首页 > 解决方案 > 是什么导致了这个 NameError: name 'ax' is not defined in my Python code?

问题描述

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

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)

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

任何人都可以告诉我什么会导致这个问题?我尝试使用其他的,但它似乎ax.plot在 Python 中的数据可视化中很常见,所以我认为我需要把它做好。谢谢!

标签: pythonnumpymatplotlib

解决方案


您需要修复最后 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)

推荐阅读