I have some problems sorting a multicategorial chart.
Some example code.
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"))
As you can see the tick 2 is before tick 1. This happens because the 'Rhino' is the first in type list, which will create the tick 0 and 2. The lion bars are added after with tick 1. But how can i sort the bars properly now?
PS. 'barmode': 'stack'
is on purpose. Even if it is not used in this test example.