pythonplotlyplotly.graph-objects

Does Plotly similar function like matplotlib fill_between


I am converting some matplotlib code to Plotly.

Does Plotly have something similar to matplotlib fill_between

Code to convert

    #   ax.fill_between(fcst_t, fcst['yhat_lower'], fcst['yhat_upper'],
    #   
                 color='#0072B2', alpha=0.2, label='Uncertainty interval')

I could manage to do something like the below, but I want to fill the area between these two lines with a particular colour.

    fig.add_trace(
           go.Scatter(x=fcst_t,y=forecast['yhat_lower'],fillcolor='grey',mode='lines+markers',name="yhat_lower"),
            row=1,col=1
    )

    fig.add_trace(
           go.Scatter(x=fcst_t,y=forecast['yhat_upper'],fillcolor='grey',mode='lines+markers',name="yhat_upper"),
            row=1,col=1
    )

enter image description here


Solution

  • go.Scatter has a fill keyword that can be used to control the fill behavior. You can read more at this documentation page or by typing help(go.Scatter).

    import plotly.graph_objects as go
    import numpy as np
    
    x = np.linspace(0, 10, 100)
    y1 = np.sin(x) + 2
    y2 = np.sin(x / 2) + 8
    fig = go.Figure([
        go.Scatter(x=x, y=y1),
        # fill between the endpoints of this trace and the endpoints of the trace before it
        go.Scatter(x=x, y=y2, fill="tonextx"),
    ])
    fig
    

    The fill should also work if the two lines have a different number of points!