You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复NameError: name 'colors' is not defined错误?

解决NameError: name 'colors' is not defined错误

错误原因

代码中多次使用colors变量(比如colors[-1]、colors[1]),但从未定义过这个变量,Python无法识别该名称,因此抛出NameError。

修复步骤

1. 定义colors变量

在代码开头导入库后,添加自定义颜色列表,示例如下:

import pandas as pd
import matplotlib.pyplot as plt

# 自定义颜色列表,可根据需求替换成任意颜色代码/名称
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']

2. (可选)直接替换为具体颜色值

如果不想单独定义变量,可以直接把所有colors[x]替换成具体颜色值,比如:

  • 将ec=colors[-1]换成ec='black'
  • 将color=colors[1]换成color='orange'

额外优化:修正图表逻辑

原代码中第二个和第三个图表标题为“With Heart Disease”和“Without Heart Disease”,但未过滤对应数据集,导致图表内容与标题不符。假设数据集中有标记患病的列(比如heart_disease,1代表患病,0代表未患病),可以修改代码如下:

import pandas as pd
import matplotlib.pyplot as plt

colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']

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

fig, ax = plt.subplots(1, 3, figsize=(14, 5), sharey=True)
l = ['Count', 'Exercise Angina']

# 提前计算各组统计结果,避免重复计算
total_angina = df.groupby('exercise angina')['age'].count()
with_disease = df[df['heart_disease'] == 1].groupby('exercise angina')['age'].count()
without_disease = df[df['heart_disease'] == 0].groupby('exercise angina')['age'].count()

total_angina.plot(kind='bar', ec=colors[-1], ax=ax[0], title='Exercise Angina Distribution', ylabel=l[0], xlabel=l[1])
with_disease.plot(kind='bar', ax=ax[1], ec=colors[-1], color=colors[1], title="With Heart Disease", xlabel=l[1])
without_disease.plot(kind='bar', ax=ax[2], ec=colors[-1], color=colors[2], title="Without Heart Disease", xlabel=l[1])

plt.tight_layout()
plt.show()

内容的提问来源于stack exchange,提问作者Juan Rodriguez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 08:25:21