Search code examples
pythonplotly

How to plot density of lines with plotly


Let's say I have a set lines (y vs. x) that are the result of a random process.

I am looking for a visualization that shows the spread of the lines.

Concretely I am looking to get an e.g. transparency-graded filled region where the opacity corresponds to the height of the histogram at that point.

Somewhat like the plotly "Filled Lines" example, except that I am not looking for hard borders to the area filled but a gradual phasing out using transparency.

One example similar to what I am looking to realize is shown in on this blog: enter image description here

I would like to plot different sets of lines (e.g. different experimental conditons) on the same plot in different colours to visually compare their results.


Solution

  • Since you're specifically asking for Plotly, one approach could be to visually represent all your results from your random process with an indiviudal line and a certain opacity.

    Plot:

    enter image description here

    Code:

    # imports
    from plotly.subplots import make_subplots
    import plotly.graph_objs as go
    import pandas as pd
    import numpy as np
    
    # random data
    np.random.seed(123)
    frame_rows = 50
    frame_cols = 500
    frame_columns = ['V_'+str(e) for e in list(range(frame_cols+1))]
    df=pd.DataFrame()
    
    for col in frame_columns:
        df[col]=np.sin(np.arange(0,frame_rows/10, 0.1)*np.random.uniform(low=0.85, high=0.99))
    
    # plotly figure
    fig=go.Figure()
    for i in range(1, frame_cols):
            #print(str(i))
            fig.add_trace(go.Scatter(x=df.index,
                                     y=df[df.columns[i]].values,
                                     showlegend=False,           # hides trace name from legend
                                     hoverinfo='skip',           # turns off hoverinfo
                                     name = None,
                                     mode = 'lines',
                                     line_color='black',
                                     opacity = 0.008
                                    )
                         )
    
    # add mean of all rows to the plot
    df_mean=df.mean(axis=1).to_frame()
    df_mean.columns=['mean']
    # show mean
    fig.add_trace(go.Scatter(x=df_mean.index, y=df_mean['mean'].values,
                              name='mean lines',
                              line_color='red',
                              line=dict(width=2),
                              mode='lines')
                 )
            
    fig.show()