Plotly: How to make a figure with multiple lines and shaded area for standard deviations?

后端 未结 2 1716
梦毁少年i
梦毁少年i 2020-12-19 16:46

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.

2条回答
  •  失恋的感觉
    2020-12-19 17:06

    I was able to come up with something similar. I will post the code here to be used by someone else or for any suggestions for improvements.

    import matplotlib,random import plotly.graph_objects as go import numpy as np

    #random color generation in plotly
    hex_colors_dic = {}
    rgb_colors_dic = {}
    hex_colors_only = []
    for name, hex in matplotlib.colors.cnames.items():
        hex_colors_only.append(hex)
        hex_colors_dic[name] = hex
        rgb_colors_dic[name] = matplotlib.colors.to_rgb(hex)
    
    data = [[1, 3, 5, 4],
            [2, 3, 5, 4],
            [1, 1, 4, 5],
            [2, 3, 5, 4]]
    #calculating mean and standard deviation
    mean=np.mean(data,axis=0)
    std=np.std(data,axis=0)
    
    #draw figure
    fig = go.Figure()
    c = random.choice(hex_colors_only)
    fig.add_trace(go.Scatter(x=np.arange(4), y=mean+std,
                                         mode='lines',
                                         line=dict(color=c,width =0.1),
                                         name='upper bound'))
    fig.add_trace(go.Scatter(x=np.arange(4), y=mean,
                             mode='lines',
                             line=dict(color=c),
                             fill='tonexty',
                             name='mean'))
    fig.add_trace(go.Scatter(x=np.arange(4), y=mean-std,
                             mode='lines',
                             line=dict(color=c, width =0.1),
                             fill='tonexty',
                             name='lower bound'))
    fig.show()
    

提交回复
热议问题