Create Leaderboard
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"
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", "VALUE": 88},
3
{"LABEL": "B", "VALUE": 12},
4
{"LABEL": "C", "VALUE": 43},
5
{"LABEL": "D", "VALUE": 43},
6
{"LABEL": "E", "VALUE": 2},
7
{"LABEL": "F", "VALUE": 87},
8
{"LABEL": "G", "VALUE": 67},
9
{"LABEL": "H", "VALUE": 111},
10
{"LABEL": "I", "VALUE": 24},
11
{"LABEL": "J", "VALUE": 123},
12
]
13
df = pd.DataFrame(data)
14
df = df.sort_values(by=["VALUE"], ascending=True) #Order will be reversed in plot
15
df
Copied!

Create the plot

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