Plotly:对多类别条形图进行排序

2021-12-01 11:36:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在整理多类别图表时遇到一些问题

一些示例代码

import pandas as pd
import plotly.graph_objects as go

data = [
    [0, "Born", 4, "Rhino"],  # commenting this line will also reverse sub category sorting
    [0, "Died", -1, "Rhino"],
    [1, "Born", 4, "Lion"],
    [1, "Died", -1, "Lion"],
    [2, "Born", 12, "Rhino"],
    [2, "Died", -5, "Lion"],
]
z_data = list(zip(*data))

df = pd.DataFrame({
    "tick": z_data[0],
    "category": z_data[1],
    "value": z_data[2],
    "type": z_data[3],
})
df = df.sort_values(by=['tick', 'category', 'value', 'type'])
print(df)
fig = go.Figure()
for t in df.type.unique():
    plot_df = df[df.type == t]
    fig.add_trace(go.Bar(
        x=[plot_df.tick, plot_df.category],
        y=abs(plot_df.value),
        name=t,
    ))
fig.update_layout({
    'barmode': 'stack',
    'xaxis': {
        'title_text': "Tick",
        'tickangle': -90,
    },
    'yaxis': {
        'title_text': "Value",
    },
})
fig.write_html(str("./diagram.html"))

uncommentedcommented

如您所见,勾号2在勾号1之前。这是因为“Rhino”是类型列表中的第一个,它将创建记号0和2。狮栏在勾选1后添加。 但是我现在怎样才能正确地分类呢

PS.'barmode': 'stack'是故意的。即使在本测试示例中未使用它