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

如何在Polars与Plotnine中设置柱状图的分类顺序?

解决分类顺序问题的两种方法

1. 在Polars DataFrame中设置分类顺序

Polars支持将列转为分类类型并指定自定义顺序,只需先定义正确的Category序列,再将对应列转为带指定顺序的分类类型即可。

修改后的完整代码:

import polars as pl
import polars.selectors as cs
from plotnine import *

# 定义符合需求的Category顺序
category_order = [
    '0-4', '5-10', '11-15', '16-20', '21-25', '26-30', 
    '31-35', '36-40', '41-45', '46-50', '51-55', '56-60', 
    '61-65', '66-70', '71-75', '76-80', '81-85', '86-90', 
    '91-95', '96-100', '101+'
]

df = pl.read_csv('https://raw.githubusercontent.com/Brinkhuis/Zorguitgaven/refs/heads/master/zorguitgaven.csv')
df = df.unpivot(cs.numeric(), index='Category')

# 将Category列转为指定顺序的分类类型
df = df.with_columns(
    pl.col('Category').cast(pl.Categorical).cat.set_ordering('physical').cat.set_categories(category_order)
)

(
    ggplot() +
    geom_bar(
        data=df.filter(pl.col('variable').is_in(['Mannen 2040', 'Vrouwen 2040'])),
        mapping=aes(x='Category', y='value', fill='variable'),
        stat='identity'
    ) +
    scale_fill_manual(values=['#007BC7', '#CA005D']) +
    coord_flip()
)

核心逻辑是用cat.set_categories()指定自定义顺序,cat.set_ordering('physical')让Polars使用你定义的物理顺序,而非默认的字典序。

2. 在Plotnine中直接设置分类顺序

如果不想修改DataFrame结构,也可以在Plotnine中通过坐标轴刻度参数指定顺序。注意因为使用了coord_flip()翻转坐标轴,原x轴的Category会变成y轴,所以要对应使用scale_y_discrete()来设置顺序。

修改后的绘图部分代码:

# 定义符合需求的Category顺序
category_order = [
    '0-4', '5-10', '11-15', '16-20', '21-25', '26-30', 
    '31-35', '36-40', '41-45', '46-50', '51-55', '56-60', 
    '61-65', '66-70', '71-75', '76-80', '81-85', '86-90', 
    '91-95', '96-100', '101+'
]

(
    ggplot() +
    geom_bar(
        data=df.filter(pl.col('variable').is_in(['Mannen 2040', 'Vrouwen 2040'])),
        mapping=aes(x='Category', y='value', fill='variable'),
        stat='identity'
    ) +
    scale_fill_manual(values=['#007BC7', '#CA005D']) +
    # 翻转坐标轴后,用scale_y_discrete指定原x轴的分类顺序
    scale_y_discrete(limits=category_order) +
    coord_flip()
)

如果不使用coord_flip(),则替换为scale_x_discrete(limits=category_order)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 13:43:11