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

如何使用Seaborn按Bug严重程度(低→高/逆序)排序直方图列?

优化Seaborn Bug严重程度直方图排序的方法

方法1:直接给displot指定order参数

不用额外生成新数据框,直接把排序后的严重程度类别传给order即可:

  • 如果严重程度是可自然排序的类型(比如数值1/2/3,或英文"Low"/"Medium"/"High"),可以直接获取排序后的唯一值:
sorted_severity = sorted(incidents['Severity'].unique())
sns.displot(data=incidents, x='Severity', order=sorted_severity)
  • 如果是自定义顺序的字符串(比如中文"低"/"中"/"高",自然排序可能不符合需求),直接手动定义顺序列表:
custom_order = ["低", "中", "高"]
sns.displot(data=incidents, x='Severity', order=custom_order)

方法2:将Severity转为有序分类变量(一劳永逸)

把严重程度列设置为有序分类类型,后续所有Seaborn绘图都会自动沿用这个顺序,无需每次指定order,是最优雅的方案:

import pandas as pd

# 定义你需要的排序顺序
severity_order = ["低", "中", "高"]
# 转换为有序分类
incidents['Severity'] = pd.Categorical(incidents['Severity'], categories=severity_order, ordered=True)

# 直接绘图,自动按设定顺序排列
sns.displot(data=incidents, x='Severity')

这种方式的优势在于,后续用countplot、barplot等其他函数时,也不用再重复设置排序逻辑,一次定义全局生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 04:54:24