How can I make the legend appear in a scatter plot (and one with error_y)

I have a simple plot

import plotly.graph_objects as go

x_data = [1, 2, 3, 4, 5]
y_data = [10, 8, 6, 4, 2]
y2_data = [3, 5, 2, 8, 10]

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=x_data,
    y=y_data,
    mode='lines+markers',  # Use 'lines+markers' mode
    name='Trace 1',
    error_y=dict(
            type='data',
            array=y2_data,
            visible=True,
            color='cyan'
        )
))
fig.update_layout(
    title='Simple Scatter Plot',
    xaxis_title='X-Axis',
    yaxis_title='Y-Axis',
)

fig.show()

This script has two problems:

  1. I want the trace name displayed β€œTrace 1”
  2. I also want to include a name for the error_y β€œError”

How can I do that?

The legend can be added by updating the layout to add a legend display. You can also add a stand-alone error bar to display a legend for the error bar.

import plotly.graph_objects as go

x_data = [1, 2, 3, 4, 5]
y_data = [10, 8, 6, 4, 2]
y2_data = [3, 5, 2, 8, 10]

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=x_data,
    y=y_data,
    mode='lines+markers',
    name='Trace 1',
))

fig.add_trace(go.Scatter(
    x=x_data,
    y=y_data,
    mode='markers',
    name='error',
    marker=dict(color='#636efa'),
    error_y=dict(
        type='data',
        array=y2_data,
        visible=True,
        color='cyan'
        )
))

fig.update_layout(
    title='Simple Scatter Plot',
    xaxis_title='X-Axis',
    yaxis_title='Y-Axis',
    showlegend=True
)

fig.show()

2 Likes