简体   繁体   中英

python: plotly set xaxis category order

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}

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: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM