Search code examples
pythonplotlyplotly-python

Plotly: How to add a horizontal scrollbar to a plotly express figure?


I'm beginning to learn more about plotly and pandas and have a multivariate time series I wish to plot and interact with using plotly.express features. I also want my plot to a horizontal scrollbar so that the initial plot is for a pre-specified initial time interval. Here's my example involving three time series along with 100K time points:

import plotly.express as px
import numpy as np
import pandas as pd

np.random.seed(123)
e = np.random.randn(100000,3)  
df=pd.DataFrame(e, columns=['a','b','c'])

df['x'] = df.index
df_melt = pd.melt(df, id_vars="x", value_vars=df.columns[:-1])
fig=px.line(df_melt, x="x", y="value",color="variable")
fig.show()

enter image description here

(For my ultimate purposes, the time series will be larger--likely 40 to 70 time series in 900K+ time points.)

This creates a graph with which I can interact using plotly.express features like zooming, panning, rectangle selection, etc.

Is there a way I can augment this so that the initial plot shows merely the first 500 time points and a scroll bar permits me to investigate what happens as time increases?

Using Mac OS 10.15.4 and Python 3.7 with IDLE. I wish to create this in IDLE and not in a Jupyter notebook environment.


Solution

  • The easiest way is to add the following to your setup:

    fig.update_layout(xaxis=dict(rangeslider=dict(visible=True),
                                 type="linear"))
    

    And you'll get:

    enter image description here

    This will enable you to both subset and pan the original figure:

    enter image description here

    Complete code:

    import plotly.express as px
    import numpy as np
    import pandas as pd
    
    np.random.seed(123)
    e = np.random.randn(100000,3)  
    df=pd.DataFrame(e, columns=['a','b','c'])
    
    df['x'] = df.index
    df_melt = pd.melt(df, id_vars="x", value_vars=df.columns[:-1])
    fig=px.line(df_melt, x="x", y="value",color="variable")
    
    # Add range slider
    fig.update_layout(xaxis=dict(rangeslider=dict(visible=True),
                                 type="linear")
    )
    
    fig.show()