How to sort legends of the scatter plot alphabetically

I am using python dash for creating a scatter plot. The legends I am getting are randomly arranged. I want to arrange them alphabetically.

I used following code:

fig = px.box(
            df,
            x=selected_x,
            y=selected_y,
            points='all',
            hover_data=hover_data,
            color=colour_by,
            width=800,
            height=600,
            labels={
                selected_y: "{} {}".format(selected_y_gene, selected_y, categoryorder='category ascending'),
                selected_x: "{} {}".format(selected_x_gene, selected_x, categoryorder='category ascending'),
            },

Hi @pr1009 and welcome to the forum! :tada:

You can specify the order of the legend with the category_order argument. In your case, it would be something similar to this:

category_orders={colour_by: np.sort(df[colour_by].unique())}

For this you need to have imported numpy as np.

Hope this helps! :four_leaf_clover:

4 Likes

Thank you soo much Celia :slight_smile: