【问题标题】:python: plotly set xaxis category orderpython:情节设置xaxis类别顺序
【发布时间】:2020-12-23 11:02:23
【问题描述】:

如何设置具有指定 xaxis 顺序的情节分类小提琴图?

这是一个示例代码。

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',
                        )
              )

functiopn 和 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}

【问题讨论】:

  • 你能分享你的映射功能吗?
  • 这是一个帮助对xaxis进行排序的字典。我在上面添加了一个示例。

标签: python plotly


【解决方案1】:

这取决于您希望如何对 df 进行排序,但您也许可以通过以下方式处理您的问题:

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()

结果:

【讨论】:

  • 虽然这仍然有效,但我很想知道有什么方法可以在没有 for 循环的情况下指定顺序?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-19
  • 2012-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
  • 1970-01-01
相关资源
最近更新 更多