Search code examples
pythonexpresssortingplotlyscatter

Ploltly express scatterplot does not allow for sorting categorical labels


It seems that setting the categoryorder of the x-axes makes px.scatter figures crash when using marginal plots

import pandas as pd
import plotly.express as px # plotly 4.9.0

df = pd.DataFrame({'x':['c', 'a', 'b'], 'y':[1,2,1]})
fig = px.scatter(df, x='x', y='y', marginal_y='box')
fig.update_xaxes(categoryorder='category ascending') # Line x
fig.show(renderer='browser')
# Only works, if line x is removed, or when parameter marginal_y='box' is removed

Is this a bug or am I missing something?


Solution

  • Try to update layout

    import pandas as pd
    import plotly.express as px # plotly 4.9.0
    
    df = pd.DataFrame({'x':['c', 'a', 'b'], 'y':[1,2,1]})
    fig = px.scatter(df, x='x', y='y', marginal_y='box')
    fig.update_layout(xaxis=dict(type='category',categoryorder='category ascending'))
    fig.show()