【问题标题】:How to fix NameError: name 'colors' is not defined如何修复 NameError:名称 \'colors\' 未定义
【发布时间】:2022-11-13 03:15:56
【问题描述】:

尝试绘制此代码但遇到此错误并且无法找到更正的解决方案:

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()

我尝试了在线确定的替代选项,并且都给出了相同的错误。

【问题讨论】:

    标签: python colors nameerror


    【解决方案1】:

    您的代码建议您有一个名为 colors 的列表,其中包含您绘制的元素的颜色,但您没有它。您可以为以下示例创建它:

    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()
    

    【讨论】:

      猜你喜欢
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多