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

如何对Seaborn水平条形图按指定列值降序排序?

解决Seaborn水平条形图降序排序问题

你之前的问题出在order参数的取值上:orderX是排序后的自杀率数值,但seaborn.barplot的order参数需要的是y轴变量(country)的排序后列表——你得告诉seaborn按什么顺序排列国家的条形。

直接用下面的代码就能实现降序排序:

# 按自杀率降序排序DataFrame,提取对应的国家列表
ordered_countries = africa_all_percent.sort_values('suicide_percent_for_all_pop', ascending=False)['country'].tolist()

# 绘制条形图并传入order参数
sns.barplot(
    data=africa_all_percent,
    y="country",
    x="suicide_percent_for_all_pop",
    palette='plasma',
    orient="h",
    order=ordered_countries
)

嫌麻烦的话,也可以把排序逻辑直接写在order参数里,省去中间变量:

sns.barplot(
    data=africa_all_percent,
    y="country",
    x="suicide_percent_for_all_pop",
    palette='plasma',
    orient="h",
    order=africa_all_percent.sort_values('suicide_percent_for_all_pop', ascending=False)['country']
)

核心逻辑是:通过sort_values对整个DataFrame按自杀率降序排列,再提取排序后的country列——这个序列就是条形图的排列顺序,传给order参数后,条形图就会按自杀率从高到低展示国家了。

内容的提问来源于stack exchange,提问作者Tuta.Tibetan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 08:12:15