How can I use Plotly to produce a line plot with a shaded standard deviation? I am trying to achieve something similar to seaborn.tsplot. Any help is appreciated.
Advertisement
Answer
The following approach is fully flexible with regards to the number of columns in a pandas dataframe and uses the default color cycle of plotly. If the number of lines exceed the number of colors, the colors will be re-used from the start. As of now px.colors.qualitative.Plotly
can be replaced with any hex color sequence that you can find using px.colors.qualitative
:
JavaScript
x
4
1
Alphabet = ['#AA0DFE', '#3283FE', '#85660D', '#782AB6', '#565656', '#1...
2
Alphabet_r = ['#FA0087', '#FBE426', '#B00068', '#FC1CBF', '#C075A6', '...
3
[ ]
4
Complete code:
JavaScript
1
68
68
1
# imports
2
import plotly.graph_objs as go
3
import plotly.express as px
4
import pandas as pd
5
import numpy as np
6
7
# sample data in a pandas dataframe
8
np.random.seed(1)
9
df=pd.DataFrame(dict(A=np.random.uniform(low=-1, high=2, size=25).tolist(),
10
B=np.random.uniform(low=-4, high=3, size=25).tolist(),
11
C=np.random.uniform(low=-1, high=3, size=25).tolist(),
12
))
13
df = df.cumsum()
14
15
# define colors as a list
16
colors = px.colors.qualitative.Plotly
17
18
# convert plotly hex colors to rgba to enable transparency adjustments
19
def hex_rgba(hex, transparency):
20
col_hex = hex.lstrip('#')
21
col_rgb = list(int(col_hex[i:i+2], 16) for i in (0, 2, 4))
22
col_rgb.extend([transparency])
23
areacol = tuple(col_rgb)
24
return areacol
25
26
rgba = [hex_rgba(c, transparency=0.2) for c in colors]
27
colCycle = ['rgba'+str(elem) for elem in rgba]
28
29
# Make sure the colors run in cycles if there are more lines than colors
30
def next_col(cols):
31
while True:
32
for col in cols:
33
yield col
34
line_color=next_col(cols=colCycle)
35
36
# plotly figure
37
fig = go.Figure()
38
39
# add line and shaded area for each series and standards deviation
40
for i, col in enumerate(df):
41
new_col = next(line_color)
42
x = list(df.index.values+1)
43
y1 = df[col]
44
y1_upper = [(y + np.std(df[col])) for y in df[col]]
45
y1_lower = [(y - np.std(df[col])) for y in df[col]]
46
y1_lower = y1_lower[::-1]
47
48
# standard deviation area
49
fig.add_traces(go.Scatter(x=x+x[::-1],
50
y=y1_upper+y1_lower,
51
fill='tozerox',
52
fillcolor=new_col,
53
line=dict(color='rgba(255,255,255,0)'),
54
showlegend=False,
55
name=col))
56
57
# line trace
58
fig.add_traces(go.Scatter(x=x,
59
y=y1,
60
line=dict(color=new_col, width=2.5),
61
mode='lines',
62
name=col)
63
)
64
# set x-axis
65
fig.update_layout(xaxis=dict(range=[1,len(df)]))
66
67
fig.show()
68