python plotly fill between range

Viewed 404

I am trying to plot learning curve in python plotly.

Instead of giving width value how can I give two bounding points?

My code:

fig = go.Figure()
fig.add_trace(
    go.Scatter(
        name="Training accuracy",
        x=train_sizes,
        y=train_mean,
        line=dict(width=0.5 ****)
    )
)
fig.add_trace(
    go.Scatter(
        name="Test accuracy",
        x=train_sizes,
        y=test_mean
    )
)

fig.show()

Instead of line=dict(width=0.5) I want fill between two list

lower_bound = array([1.        , 0.98103215, 0.98735476, 0.99173554, 0.99337748,
       0.99447514, 0.98769115, 0.98232999, 0.9847865 , 0.98679868])
upper_bound = array([1.        , 0.99674563, 0.99783042, 0.99173554, 0.99337748,
       0.99447514, 0.99658558, 0.9901218 , 0.98825271, 0.98679868])

I can do it with matplotlib however want to do it in plotly, any help?

Thanks in advance!

1 Answers

This is outlined pretty nicely in the Plotly documentation on continuous error bands. Another scatter plot is added where they go through the upper bounds in order, then the lower bounds in reverse order and fill in this shape.

Although you did not supply train_sizes and the train_mean arrays, I'll just choose some values that fall between the lower_bound and upper_bound to illustrate the concept.

import numpy as np
import pandas as pd
import plotly.graph_objects as go

lower_bound = np.array([1.        , 0.98103215, 0.98735476, 0.99173554, 0.99337748,
       0.99447514, 0.98769115, 0.98232999, 0.9847865 , 0.98679868])
upper_bound = np.array([1.        , 0.99674563, 0.99783042, 0.99173554, 0.99337748,
       0.99447514, 0.99658558, 0.9901218 , 0.98825271, 0.98679868])

## create some sample train_sizes, train_mean, test_mean arrays
np.random.seed(42)
train_sizes = np.linspace(10,100,10)
train_mean = [1, 0.985, 0.990, 0.99173554, 0.99337748, 0.99447514, 0.995, 0.985, 0.986, 0.98679868]
## make the test mean lower than the train mean
test_mean = train_mean - np.random.normal(loc=0.10, scale=0.02, size=10)

fig = go.Figure()

## add error bounds
## concatenate x going forward, then backwards
## concatenate upper bounds going forward, then lower bounds going backwards
fig.add_trace(
    go.Scatter(
        x=np.concatenate([train_sizes,train_sizes[::-1]]), 
        y=np.concatenate([upper_bound,lower_bound[::-1]]),
        fill='toself',
        fillcolor='rgb(255,179,179)',
        line=dict(color='rgba(255,255,255,0)'),
        hoverinfo="skip",
        showlegend=False
    )
)
fig.add_trace(
    go.Scatter(
        name="Training accuracy",
        x=train_sizes,
        y=train_mean,
        # line=dict(width=0.5 ****)
    )
)

fig.add_trace(
    go.Scatter(
        name="Test accuracy",
        x=train_sizes,
        y=test_mean
    )
)

fig.show()

enter image description here

Related