[Python] Order of columns in a plotnine bar plot using a polars dataframe

Discussão em 'Python' iniciado por Stack, Agosto 4, 2025.

  1. Stack

    Stack Membro Participativo

    I'm quite new to the packages polars and plotnine and have the following code:

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

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

    (
    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()
    )


    It runs without errors. However, the Category order is not right.

    [​IMG]

    The "5-10" value show be one "row 3".

    My questions:

    1. Is there a way to set the categorical order in a polars dataframe to fix this?
    2. Is there a way to set the categorical order in plotnine?

    Continue reading...

Compartilhe esta Página