plotly express reorders categorical x-axis scatter if I add a color

Viewed 271

Imagine I have a set of observations, ordered in rows. Each observation has quantitative and ordinal measurements associated with it.

The observations are ordered based on a quantitative measurement (ie order is important), but because order not magnitude matters in that dimension I want to use a categorical x axis scatter instead of a numerical x axis scatter.

This all works fine as long as I don't add a 'color' to the plotly express scatter:

import pandas as pd
import plotly.express as px
metrics = ['m1', 'm2', 'm3', 'm4']
a = ['a', 'b', 'd', 'b']
b = [1,2,3,4]
c = [4,5,6,7]
d = ['w','x','y','z']
data = pd.DataFrame(data=[a,b,c,d], index=metrics).T

The above code will generate a plotly chart where the observations are plotted in the order they are found in the dataframe: px.scatter(data, y='m2', x='m4').

correct ordering of datapoints

However, if I add a color, via px.scatter(data, y='m2', x='m4', color='m1'), the order is jumbled up!

incorrect ordering of datapoints if i add a color/hue

Any idea how to fix this?

1 Answers

You can use parameter 'category_order', and pass a dictionary in the dimension you want to specify order: eg in this case add parameter category_orders={'m4':d}

Related