user71812
user71812

Reputation: 457

What causes this NameError: name 'ax' is not defined in my Python code?

So I want to build a line chart with this 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)

But it only produces this error message: NameError: name 'ax' is not defined.

Anybody can tell me what can cause this problem? I tried using others, but it appears that ax.plot is very common in data visualization in Python, so I think I need to get this right. Thank you!

Upvotes: 4

Views: 28679

Answers (1)

Jmonsky
Jmonsky

Reputation: 1519

You need to fix your indentation on the last 3 lines, then call the function seperately.

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)

Upvotes: 6

Related Questions