Dana_Miles
Dana_Miles

Reputation: 429

Confidence interval and legends

is there a way to fully connect a confidence interval (CI) with a graph? Currently, when I use the suggested way for an CI there is an issue:

  1. The line in the legend does not show the CI
  2. If i disable the line in the legend, the CI still is visible in the plot

Is there a way to make the line and CI disappear at the same time? Alternatively, can I prevent the user from being able to turn any lines off in the legend (so the CI never will be displayed without a line)?

Thank you!

import plotly.graph_objects as go

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x_rev = x[::-1]

# Line 1
y1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y1_upper = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
y1_lower = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y1_lower = y1_lower[::-1]

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=x+x_rev,
    y=y1_upper+y1_lower,
    fill='toself',
    fillcolor='rgba(0,100,80,0.2)',
    line_color='rgba(255,255,255,0)',
    showlegend=False,
    name='Line1',
))
fig.add_trace(go.Scatter(
    x=x, y=y1,
    line_color='rgb(0,100,80)',
    name='Fair',
))

fig.update_traces(mode='lines')
fig.show()

Upvotes: 2

Views: 473

Answers (1)

rpanai
rpanai

Reputation: 13437

all you need here is to group legends. See the documentations. In your case you could modify your code as following

import plotly.graph_objects as go

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x_rev = x[::-1]

# Line 1
y1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y1_upper = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
y1_lower = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y1_lower = y1_lower[::-1]

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=x+x_rev,
    y=y1_upper+y1_lower,
    fill='toself',
    fillcolor='rgba(0,100,80,0.2)',
    line_color='rgba(255,255,255,0)',
    showlegend=False,
    name='Line1',
    legendgroup="group_fair"
))
fig.add_trace(go.Scatter(
    x=x, y=y1,
    line_color='rgb(0,100,80)',
    name='Fair',
    legendgroup="group_fair"
))

fig.update_traces(mode='lines')
fig.show()

Upvotes: 2

Related Questions