Search code examples
pythonpython-3.xplotlyplotly-dashdashboard

How do I use range breaks and scattergl in the same plot?


I have this plot-

fig = go.Figure()

fig.add_trace(
    go.Scattergl(x=list(df.Date), y=list(df.Measure)), row = 1, col = 1)
    
fig.update_layout(
    xaxis=dict(
        rangeselector=dict(
            buttons=list([
                dict(count=1,
                     label="1m",
                     step="month",
                     stepmode="backward")
            ])
        ),
        rangeslider=dict(
            visible=True
        ),
        type="date"
    )
)

The code works fine when I remove the range-breaks, but stops working when I add them in.

Is it possible to use range breaks and scatter gl in the same plot?


Solution

  • Due to official documentation range breaks on time-series axes are not yet supported in the WebGL-powered version of certain SVG-powered trace types, e.g. scattergl (plotly version 5.10.0). So to make it work we have to switch to the go.Scatter.

    import pandas as pd
    import plotly.graph_objects as go
    
    # Dummy data
    s = pd.date_range(end=pd.Timestamp('2022-08-27'), periods=100, freq='D')
    df = pd.DataFrame({'Date':s, 'Measure': s.day})
    
    # Plot
    fig = go.Figure()
    
    fig.add_trace(
        # replace Scattergl with the Scatter object
        go.Scatter(x=df.Date, y=df.Measure))
    
    fig.update_xaxes(
        rangebreaks=[
            dict(bounds=["sat", "mon"]), # skip weekends
        ],
        rangeselector=dict(
            buttons=list([
                dict(count=1,
                     label="1m",
                     step="month",
                     stepmode="backward")
            ])
        ),
        rangeslider=dict(
            visible=True
        ),
        type="date"
    )
    
    fig.show()
    

    image