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

如何为seaborn histplot的欺诈与非欺诈类别设置不同颜色?

解决Seaborn Histplot欺诈与非欺诈类别颜色相同的问题

问题原因

你分开两次调用histplot绘制两组数据时,Seaborn默认会使用同一套调色板的默认颜色,导致两组颜色重复。可以通过两种方式解决:


方案1:显式指定每组颜色

直接在两次histplot调用中添加color参数,为欺诈和非欺诈数据分别设置不同颜色:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np 

plt.figure(figsize=(15,8))
# 为欺诈数据指定红色
ax = sns.histplot(x='type', data=df[df.isFraud == 1], stat='percent', multiple='dodge', common_norm=False, bins=25, color='#ff4136')
# 为非欺诈数据指定青色
ax = sns.histplot(x='type', data=df[df.isFraud == 0], stat='percent', multiple='dodge', common_norm=False, bins=25, color='#39cccc')
ax.set_ylabel('Percentage in Each Type')
ax.set_xlabel('Transaction Type')  # 修正原代码错误:x轴是交易类型而非金额
plt.legend(labels=['Fraud', 'Not Fraud'])
plt.show()

方案2:使用hue参数(更推荐)

无需拆分数据集,直接通过hue='isFraud'让Seaborn自动根据欺诈标签分组并分配颜色,代码更简洁规范:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np 

plt.figure(figsize=(15,8))
# 用hue区分欺诈状态,自动分配不同颜色
ax = sns.histplot(x='type', hue='isFraud', data=df, stat='percent', multiple='dodge', common_norm=False, bins=25)
ax.set_ylabel('Percentage in Each Type')
ax.set_xlabel('Transaction Type')
# 替换图例标签为易懂名称
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, ['Not Fraud', 'Fraud'])
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 07:25:18