plotly_express icon indicating copy to clipboard operation
plotly_express copied to clipboard

Allow specifying category order for legends in stacked bar plots

Open alecfwilson opened this issue 6 years ago • 2 comments

I'd like to be able to set the order in which the items in color stack. For example, I'd like to make Sun the top value of this plot:

tips = px.data.tips()

fig = px.bar(
    tips,
    x="sex",
    y="total_bill",
    color="day",
    category_orders={
        "day": [
            "Mon",
            "Tue",
            "Wed",
            "Thu",
            "Fri",
            "Sat",
            "Sun"
        ]
    },
)
fig

but it returns: image

I thought category_order would handle this, but it does not.

alecfwilson avatar Jul 18 '19 23:07 alecfwilson

Actually I think it does, it’s just that in the dataset it’s spelled “Thur” not “Thu” and the order of the legend is from the bottom of the stack. If you want the order of the legend to go the other way you can add something like .update_layout(legend_traceorder=“reversed”)

nicolaskruchten avatar Jul 18 '19 23:07 nicolaskruchten

Ah, that did solve the example I provided. However, passing a color_discrete_map seems to override it, at least with a different dataset I have been using:

fig = px.bar(
    adf,
    x="x",
    y="y",
    color="color",
    category_orders={
        "y": [
            "a",
            "b",
            "c",
            "d",
            "e",
            "f",
        ]
    },
    barmode="relative",
    opacity=1,
    color_discrete_map={
            "a": "rgb(31,120,180)",
            "b": "rgb(166,206,227)",
            "c": "rgb(51,160,44)",
            "d": "rgb(178,223,138)",
            "e": "rgb(255,127,0)",
            "f": "rgb(253,191,111)",
        },
)
fig

returns image

alecfwilson avatar Jul 19 '19 00:07 alecfwilson