'Sort grouped barchart with plotly

I am trying to create a grouped bar chart, which is working with my code so far. However, I can't find a way to sort the groupings among each other, how is that possible with plotly?

Example data of bar_df:

        4061    4144    4181    4331
lr      45.9089 65.0693 37.0036 47.3485
knn     64.8903 87.25   48.278  81.9212
bay_r   51.9641 63.5313 39.7762 46.4237
svr     52.7827 63.4806 37.032  46.1108

Current Code for plot:

partners = bar_df.columns
fig = go.Figure()
for algo in ["lr","knn","bay_r","svr"]:
    fig.add_trace(go.Bar(
        x=partners,
        y=bar_df[bar_df.index == algo].values[0],
        name=algo,
        opacity=0.75
    ))
fig.update_layout(
    width=1550, 
    height=450,
    barmode='group',
    title={
        'text': f'Performance Modell-Vergleich',
        'y': 0.9,
        'x': 0.5,
    },
    yaxis_title="MAE",
    xaxis_tickangle=-45
)
fig.show()

Image of the result of the current code:

enter image description here



Solution 1:[1]

You have not defined your order. An approach is to use https://pandas.pydata.org/docs/reference/api/pandas.CategoricalIndex.html to be able to define the order of the categories.

import pandas as pd
import plotly.express as px
import io
df = pd.read_csv(io.StringIO("""        4061    4144    4181    4331
lr      45.9089 65.0693 37.0036 47.3485
knn     64.8903 87.25   48.278  81.9212
bay_r   51.9641 63.5313 39.7762 46.4237
svr     52.7827 63.4806 37.032  46.1108"""), sep="\s+")

# use pandas categorical to sort categories
df = df.set_index(pd.CategoricalIndex(df.index, ordered=True, categories=['svr', 'bay_r', 'knn', 'lr'])).sort_index()

# create figure with px, it's simpler
px.bar(df.reset_index().melt(id_vars="index"), color="index", x="variable", y="value").update_layout(
    # width=1550, 
    height=450,
    barmode='group',
    title={
        'text': f'Performance Modell-Vergleich',
        'y': 0.9,
        'x': 0.5,
    },
    yaxis_title="MAE",
    xaxis_tickangle=-45
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rob Raymond