python: plotly set xaxis category order

Viewed 627

How to set a plotly categorical violinplot with specified xaxis order?

Here is an example code.

ordered_x = df['target']
ordered_x = sorted(ordered_x, key=lambda x: mapping[x])
fig.add_trace(go.Violin(x=df['target'],
                        y=df[feature],
                        name='test',
                        side='positive',
                        )
              )

Example of mapping functiopn and df['target'].

df['target'] = ['a', 'this is a target', 'this is also a target']
mapping = {'a': 1, 'this is a target': 3, 'this is also a target': 2}
1 Answers

It depend of how you want to sort your df, but you maybe you can handle your problem with:

import plotly.graph_objects as go
import pandas as pd

fig = go.Figure()

data = {'targets':['targ1','targ2','targ1','targ3','targ2','targ1','targ4','targ3','targ4'], 'features':[1,2,3,4,5,6,7,8,9]}

df=pd.DataFrame(data)

#1-sort the df
df.sort_values(by=['targets'],inplace=True)


#2-plot the violin for each value
#To avoid repeated items in graph and legend
targets=df['targets'].unique().tolist()

for target in targets:

    fig.add_trace(go.Violin(x=df['targets'][df['targets'] == target],
                            y=df['features'][df['targets'] == target],
                            name=target,
                            side='positive',
                            box_visible=True,
                            meanline_visible=True, ))


fig.show()

Result: enter image description here

Related