Sort plotly express bar chart by specific series

Hello everyone.
I have a chart that displays some values. I add target labels by value and a trigger point to it.
How can I sort the chart by decreasing value ignoring the target values?

def test_g(url):
    data = [
        {'code':'l1','value': 1, 'target': 2, 'trigger': 3},
        {'code':'l2','value': 3, 'target': 2, 'trigger': 3},
        {'code':'l3','value': 2, 'target': 4, 'trigger': 5},
        {'code':'l4','value': 2, 'target': 1, 'trigger': 2},
        {'code':'l5','value': 6, 'target': 2, 'trigger': 3},
    ]

    # Creates DataFrame.
    df = pd.DataFrame(data)
    fig = px.bar(df, x="code", y="value", text="value", text_auto=True)
    fig.add_trace(go.Scatter(
        mode='markers',
        x=df["code"], y=df["target"],
        marker_symbol="line-ew",
        marker=dict(line=dict(color='Lightgreen', width=3)),
        name="Standart", showlegend=True,
    ))
    fig.add_trace(go.Scatter(
        mode='markers',
        x=df["code"], y=df["trigger"],
        marker_symbol="line-ew",
        marker=dict(line=dict(color='Red', width=3)),
        name="Trigger point", showlegend=True,
    ))
    fig.update_xaxes(categoryorder='category descending')
    return fig

Now it looks like this:


I tried doing fig.update_xaxes(categoryorder=‘total descending’), but that’s even further from what I need.

Hi… Just plotting by default, I get this chart… and I guess, what you’re looking for:

But in case that you couldn’t replicate…
I’ve just added a line of code: category_orders=dict(code=['l3','l5','l1','l2','l4']) inside px.bar and this is what you get:

I’ll hope this is useful.

Well, almost.
I wanted to sort by decreasing blue column and thought there was some convenient, short way.
I read your comment and did it like this.

sorted_codes = [item['code'] for item in sorted(data, key=lambda x: x['value'], reverse=True)]
fig = px.bar(df, x="code", y="value", text="value", text_auto=True, category_orders={"code": sorted_codes})

Now it’s good.
Thanks a lot =)

Another way is to sort the DataFrame before plotting.

# Sort the DataFrame by the 'value' column in descending order 
df_sorted = df.sort_values(by='value', ascending=False)