对于pandas数据框中的列数,以下方法完全灵活,并使用plotly的默认颜色周期。如果行数超过颜色数,将从一开始就重新使用颜色。截至目前
px.colors.qualitative.Plotly,您可以使用
px.colors.qualitative以下任何十六进制颜色序列替换:
Alphabet = ['#AA0DFE', '#3283FE', '#85660D', '#782AB6', '#565656', '#1...Alphabet_r = ['#FA0087', '#FBE426', '#B00068', '#FC1CBF', '#C075A6', '...[...]
完整的代码:
# importsimport plotly.graph_objs as goimport plotly.express as pximport pandas as pdimport numpy as np# sample data in a pandas dataframenp.random.seed(1)df=pd.Dataframe(dict(A=np.random.uniform(low=-1, high=2, size=25).tolist(), B=np.random.uniform(low=-4, high=3, size=25).tolist(), C=np.random.uniform(low=-1, high=3, size=25).tolist(), ))df = df.cumsum()# define colors as a list colors = px.colors.qualitative.Plotly# convert plotly hex colors to rgba to enable transparency adjustmentsdef hex_rgba(hex, transparency): col_hex = hex.lstrip('#') col_rgb = list(int(col_hex[i:i+2], 16) for i in (0, 2, 4)) col_rgb.extend([transparency]) areacol = tuple(col_rgb) return areacolrgba = [hex_rgba(c, transparency=0.2) for c in colors]colCycle = ['rgba'+str(elem) for elem in rgba]# Make sure the colors run in cycles if there are more lines than colorsdef next_col(cols): while True: for col in cols: yield colline_color=next_col(cols=colCycle)# plotly figurefig = go.Figure()# add line and shaded area for each series and standards deviationfor i, col in enumerate(df): new_col = next(line_color) x = list(df.index.values+1) y1 = df[col] y1_upper = [(y + np.std(df[col])) for y in df[col]] y1_lower = [(y - np.std(df[col])) for y in df[col]] y1_lower = y1_lower[::-1] # standard deviation area fig.add_traces(go.Scatter(x=x+x[::-1], y=y1_upper+y1_lower, fill='tozerox', fillcolor=new_col, line=dict(color='rgba(255,255,255,0)'), showlegend=False, name=col)) # line trace fig.add_traces(go.Scatter(x=x, y=y1, line=dict(color=new_col, width=2.5), mode='lines', name=col) )# set x-axisfig.update_layout(xaxis=dict(range=[1,len(df)]))fig.show()


