Search code examples
pythonplotlydata-visualizationcustomizationplotly-python

Plotly: Range slider not being displayed for row count > 500


enter image description here

As is visible from the image, the scaffolding for the rangeslider is generated but the trace inside it is not. It is also fully functional otherwise. With some experiment, I found that only if you set the no. of rows to 500 or less, it displays correctly. Is there a way to display it for rows more than that? Here is the code to reproduce-

size = 501 #change this to change no. of rows

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

df = {'date': pd.date_range(start='2021-01-01', periods=size, freq='D'),
     'new_cases': np.random.random(size=size),
     'new_cases_smoothed': np.random.random(size=size)}

df = pd.DataFrame(df)
fig = px.line(df, x='date', y=['new_cases','new_cases_smoothed'])
fig.update_layout(xaxis=dict(rangeslider=dict(visible=True),type="date"))
fig.show()

Solution

  • This works in graph_objects

    size = 501 #change this to change no. of rows
    
    import numpy as np
    import pandas as pd
    import plotly.express as px
    import plotly.graph_objects as go
    
    df = {'date': pd.date_range(start='2021-01-01', periods=size, freq='D'),
         'new_cases': np.random.random(size=size),
         'new_cases_smoothed': np.random.random(size=size)}
    
    df = pd.DataFrame(df)
    # fig = px.line(df, x='date', y=['new_cases','new_cases_smoothed'])
    fig = go.Figure(data=[go.Scatter(x=df["date"], y=df[c], name=c) for c in ['new_cases','new_cases_smoothed']])
    fig.update_layout(xaxis={"rangeslider":{"visible":True},"type":"date",
                            "range":[df.tail(50)["date"].min(),df.tail(50)["date"].max()]})
    fig.show()