Create Vertical Barchart stacked
Tags: #plotly #chart #verticalbarchart #group #dataviz #snippet
Author: Florent Ravenel

Input

Import libraries

1
import naas
2
import plotly.graph_objects as go
3
import pandas as pd
Copied!

Variables

1
title = "Sales Evolution (stacked)"
2
3
# Output paths
4
output_image = f"{title}.png"
5
output_html = f"{title}.html"
Copied!

Get data

1
x_axis = [1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012]
2
y_axis_value1 = [219, 146, 112, 127, 124, 180, 236, 207, 236, 263, 350, 430, 474, 526, 488, 537, 500, 439]
3
y_axis_value2 = [16, 13, 10, 11, 28, 37, 43, 55, 56, 88, 105, 156, 270, 299, 340, 403, 549, 499]
4
5
df1 = pd.DataFrame(zip(x_axis, y_axis_value1), columns=["LABEL", "VALUE"])
6
df1["GROUPS"] = "USA"
7
8
df2 = pd.DataFrame(zip(x_axis, y_axis_value2), columns=["LABEL", "VALUE"])
9
df2["GROUPS"] = "Rest of world"
10
11
df = pd.concat([df1, df2])
12
df
Copied!

Model

Create Vertical Barchart stacked

1
def create_barchart(df, label, groups, value, title):
2
fig = go.Figure()
3
4
list_groups = df[groups].unique()
5
for group in list_groups:
6
tmp_df = df[df[groups] == group]
7
fig.add_trace(go.Bar(x=tmp_df[label],
8
y=tmp_df[value],
9
name=group))
10
fig.update_layout(
11
title=title ,
12
plot_bgcolor="#ffffff",
13
width=1200,
14
height=800,
15
xaxis_tickfont_size=14,
16
legend=dict(
17
bgcolor='white',
18
bordercolor='white'
19
),
20
barmode='stack',
21
bargap=0.1, # gap between bars of adjacent location coordinates.
22
bargroupgap=0.1 # gap between bars of the same location coordinate.
23
)
24
config = {'displayModeBar': False}
25
fig.show(config=config)
26
return df
27
28
fig = create_barchart(df, label="LABEL", groups="GROUPS", value="VALUE", title=title)
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