Create Heatmap
Tags: #plotly #chart #heatmap #dataviz #snippet
Author: Florent Ravenel

Input

Import libraries

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

Variables

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

Get data

1
data = [[54.25, 65, 52, 51, 49],
2
[20, 16, 60, 80, 30],
3
[30, 60, 51, 59, 20],
4
[40, 30, 12, 25, 20]]
5
df = pd.DataFrame(data)
6
df
Copied!

Model

Create Heatmap

1
config = {'displayModeBar': False}
2
3
def update_layout(fig, title=None, plot_bgcolor=None, width=1200, height=800, showlegend=None, margin=None):
4
fig.update_layout(
5
title=title,
6
plot_bgcolor=plot_bgcolor,
7
width=width,
8
margin=margin,
9
height=height,
10
showlegend=showlegend)
11
return fig
12
13
def heatmap(df,
14
x,
15
y,
16
x_label,
17
y_label,
18
color,
19
colorscale=[[0, "#d94228"],[0.5, "#d94228"],[0.5, "#5ee290"],[1.0, "#5ee290"]],
20
title=None,
21
margin=None):
22
fig = go.Figure()
23
fig = px.imshow(df,
24
labels=dict(x=x_label, y=y_label, color=color),
25
x=x,
26
y=y)
27
fig.update_xaxes(side="top")
28
fig.update_traces(xgap=5, selector=dict(type='heatmap'))
29
fig.update_traces(ygap=5, selector=dict(type='heatmap'))
30
fig.update_traces(dict(showscale=False,
31
coloraxis=None,
32
colorscale=colorscale),
33
selector={'type':'heatmap'})
34
fig = update_layout(fig, title=title, margin=margin)
35
fig.show(config=config)
36
return fig
37
38
fig = heatmap(df,
39
x=['Global', 'Americas', 'EMEA', 'Asia', 'Oceania'],
40
y=['Product 1', 'Product 2', 'Product 3', 'Product 4'],
41
x_label="Business lines",
42
y_label="Products",
43
color="Sales",
44
title=title,
45
margin=dict(l=0, r=0, t=150, b=50))
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