How to fix NameError: name 'colors' is not defined

Question:

Trying to plot this code but encountering this error and unable to find resolution of correcting:

df = pd.read_csv("./train.csv")

# Bar plot for exercise induced angina by heart disease.
# Y: Yes, N: No
fig, ax=plt.subplots(1, 3, figsize=(14, 5), sharey=True)
l = ['index', 'exercise angina']
df.groupby(by=['exercise angina']).count()['age'].plot(kind='bar', ec=colors[-1], ax=ax[0], title='Exercise Angina by Heart Disease', ylabel=l[0], xlabel=l[1])
df.groupby(by=['exercise angina']).count()['age'].plot(kind='bar', ax=ax[1],  ec=colors[-1], color=colors[1], title="With Heart Disease",xlabel=l[1])
df.groupby(by=['exercise angina']).count()['age'].plot(kind='bar', ax=ax[2],   ec=colors[-1], color=colors[2], title="Without Heart Disease", xlabel=l[1])

plt.show()

I have tried alternative options identified online and all giving same error.

Asked By: Juan Rodriguez

||

Answers:

You code suggests you have a list named colors, containing the color of elements you graph, but you don’t have it. You can create it for examples like this:

df = pd.read_csv("./train.csv")
colors = ["red", "green", "blue", "grey"]

# Bar plot for exercise induced angina by heart disease.
# Y: Yes, N: No
fig, ax=plt.subplots(1, 3, figsize=(14, 5), sharey=True)
l = ['index', 'exercise angina']
df.groupby(by=['exercise angina']).count()['age'].plot(kind='bar', ec=colors[-1], ax=ax[0], title='Exercise Angina by Heart Disease', ylabel=l[0], xlabel=l[1])
df.groupby(by=['exercise angina']).count()['age'].plot(kind='bar', ax=ax[1],  ec=colors[-1], color=colors[1], title="With Heart Disease",xlabel=l[1])
df.groupby(by=['exercise angina']).count()['age'].plot(kind='bar', ax=ax[2],   ec=colors[-1], color=colors[2], title="Without Heart Disease", xlabel=l[1])

plt.show()
Answered By: Dimitrius
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.