这是什么原因导致我的Python代码出现了NameError: name 'ax' is not defined?

4

我想要用这段代码创建一条折线图:

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

有人能告诉我是什么原因导致了这个问题吗? 我尝试使用其他的内容,但似乎在Python数据可视化中ax.plot非常常见,所以我认为我需要弄清楚这点。 谢谢!


ax 在函数 lineplot 内被定义,而你甚至没有调用该函数... - Jody Klymak
1个回答

6
你需要修正最后三行的缩进,然后单独调用该函数。
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)

啊,我明白了。非常感谢你的帮助! - user71812

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接