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

Matplotlib箱线图自定义颜色不生效问题求助

解决pandas箱线图箱体颜色不生效的问题

你遇到的问题是因为pandas的boxplot方法中,color参数仅控制线类元素(箱线、中位数线、须线等)的颜色,而箱体填充色需要手动给返回的patch对象赋值——你已经设置了patch_artist=True,这是开启填充的前提,接下来只需要遍历箱体对象分配颜色即可。

修改后的完整代码

import matplotlib.pyplot as plt

# 选择要绘制的列
columns_to_plot = ['Customer_Age', 'Months_on_book', 'Credit_Limit', 'Total_Revolving_Bal', 'Avg_Open_To_Buy', 'Total_Trans_Amt', 'Total_Trans_Ct']

# 箱线图样式配置
boxprops = {'linewidth': 2}
medianprops = {'linewidth': 2, 'color': 'orange'}
whiskerprops = {'linewidth': 2}
flierprops = {'marker': 'o', 'markersize': 5, 'alpha': 0.5}
capprops = {'linewidth': 2}

fig, ax = plt.subplots(figsize=(12,8))

colors = ['lightblue', 'lightgreen', 'lavender', 'pink', 'lightyellow', 'lightcoral', 'lightsalmon']

# 绘制箱线图,patch_artist=True开启箱体填充
bp = BankChurners[columns_to_plot].boxplot(ax=ax, patch_artist=True, boxprops=boxprops, medianprops=medianprops, whiskerprops=whiskerprops, flierprops=flierprops, capprops=capprops)

# 给每个箱体分配对应颜色
for box, color in zip(bp['boxes'], colors):
    box.set_facecolor(color)

# 添加标题和标签
plt.title('客户数据箱线图', fontsize=16)
plt.ylabel('数值', fontsize=14)
plt.xticks(rotation=45, fontsize=12)

# 添加网格线
plt.grid(axis='y', linestyle='--', alpha=0.7)

# 显示图表
plt.show()

关键说明

  • bp['boxes']是pandas返回的箱线图对象中,所有箱体的patch集合,遍历它并和你的颜色列表一一对应,就能给每个箱体设置独立填充色。
  • 如果需要统一箱体颜色,直接给单个box设置set_facecolor即可,不用遍历。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:52:35