Discrete colors in px.scatter ascending order integers

I am making scatter plot where I want the color to depend on a discrete value. Exactly as in
Discrete colors in Python, I convert the integer value to a string. However, just as in the example (third figure), the integer values are not sorted in the legend.

My question is therefore: How can you sort the legend for integer values in the legend after converting them to strings?

Hi @joostgob,

Are you using plotly.express?

I’m not 100% sure, but with plotly.graph_objects you could add each trace in the correct order. Doing so, the legend should be sorted.

I use plotly.express. I simply transform β€˜feature1’ to an integer, so I do not see how to loop over all traces here.

df['feature1'] = df['feature1'] .astype(str)
fig1 = px.scatter(df, x = 'cost', y = 'score', color='feature1',
                      facet_col='feature2', facet_row='feature3')

Not sure if this helps, but try sorting your df ascending by your column feature1 before creating the figure.

Great hack, seems to work!

Yeah, it’s not a hack, actually.

Plotly express does some work for you under the hood like grouping your dataframe and plot each group as plotly.graph_objects trace.

I assumed the grouping to be in sequential order of the unique values found in your feature1 column. By sorting the column, you assured the order to be ascending. You could try sorting it descending, if the order of the traces is reversed, it backs my theory :joy:

1 Like