Create Leaderboard stacked
Tags: #plotly #chart #horizontalbar #dataviz #snippet
Author: Florent Ravenel
Learn more on the Plotly doc : https://plotly.com/python/horizontal-bar-charts/

Input

Import libraries

1
import plotly.express as px
2
import pandas as pd
Copied!

Variables

1
title = "Leaderboard_stacked"
2
3
# Output paths
4
output_image = f"{title}.png"
5
output_html = f"{title}.html"
Copied!

Model

Get data model

1
data = [
2
{"LABEL": "A", "GROUPS": "1", "VALUE": 88},
3
{"LABEL": "A", "GROUPS": "2", "VALUE": 12},
4
{"LABEL": "B", "GROUPS": "1", "VALUE": 43},
5
{"LABEL": "B", "GROUPS": "2", "VALUE": 43},
6
{"LABEL": "C", "GROUPS": "1", "VALUE": 2},
7
{"LABEL": "C", "GROUPS": "2", "VALUE": 87},
8
{"LABEL": "D", "GROUPS": "1", "VALUE": 67},
9
{"LABEL": "D", "GROUPS": "2", "VALUE": 111},
10
{"LABEL": "E", "GROUPS": "1", "VALUE": 24},
11
{"LABEL": "E", "GROUPS": "2", "VALUE": 123},
12
]
13
df = pd.DataFrame(data)
14
df
Copied!

Prep data

1
# Calc VALUE TOTAL by LABEL to sort bar
2
def prep_data(df):
3
# Calc total
4
df_tot = df.groupby(["LABEL"], as_index=False).agg({"VALUE": "sum"}).rename(columns={"VALUE": "VALUE_TOT"})
5
6
# Merge dataframe
7
df = pd.merge(df, df_tot, on="LABEL")
8
9
# Sort values
10
df = df.sort_values(by=["VALUE_TOT", "LABEL"])
11
return df
12
13
df_plot = prep_data(df)
14
df_plot
Copied!

Create the plot

1
def create_barchart(df, label, groups, value):
2
last_value = '{:,.0f}'.format(df[value].sum())
3
colors = {
4
"1": "blue",
5
"2": "green",
6
}
7
fig = px.bar(df,
8
y=label,
9
color=groups,
10
x=value,
11
orientation='h',
12
color_discrete_map=colors,
13
text=value)
14
fig.update_layout(
15
title=f"<b>Ranking by label</b><br><span style='font-size: 13px;'>Total value: {last_value}</span>",
16
title_font=dict(family="Arial", size=18, color="black"),
17
legend_title="Packs",
18
legend_title_font=dict(family="Arial", size=11, color="black"),
19
legend_font=dict(family="Arial", size=10, color="black"),
20
font=dict(family="Arial", size=12, color="black"),
21
plot_bgcolor="#ffffff",
22
width=1200,
23
height=800,
24
xaxis_title=None,
25
xaxis_showticklabels=False,
26
yaxis_title=None,
27
margin_pad=10,
28
margin_t=100,
29
)
30
fig.update_yaxes(categoryarray=df[label].unique())
31
# Display fig
32
config = {'displayModeBar': False}
33
fig.show(config=config)
34
return fig
35
36
fig = create_barchart(df_plot, "LABEL", "GROUPS", "VALUE")
Copied!

Output

Export in PNG and HTML

1
fig.write_image(output_image, width=1200)
2
fig.write_html(output_html)
Copied!

Generate shareable assets

1
link_image = naas.asset.add(output_image)
2
link_html = naas.asset.add(output_html, {"inline":True})
3
4
#-> Uncomment the line below to remove your assets
5
# naas.asset.delete(output_image)
6
# naas.asset.delete(output_html)
Copied!
Copy link
Edit on GitHub