Changing the legend names on plotly express line chart

Hello Everyone,
i am using numpy array [3,10] to plot the line chart using plotly express. The problem is i am not able to rename the legend names which are ‘wide_variable_0’ (default) and so on, The line plot variable is driven by dropdown menu. i have already tried the ‘label’ property but its not working.
please find attached screenshot and demo code for referance .
Any suggestion would be appreciated on how can i change the default legend names.
Have a nice day ahead

import dash
import numpy as np
import dash_html_components as html
import dash_core_components as dcc
import plotly.graph_objects as go
import plotly.express as px

app = dash.Dash(name)

line_plot = go.Figure()

app.layout = html.Div([
html.H1(‘Line Plot’),

html.Div(
    dcc.Dropdown(
        id='page-1-dropdown',
        options=[{'label': i, 'value': i} for i in ['first','second','third']],
        value='first'
)),
html.Div(
dcc.Graph(id='line-plot',
          figure=line_plot))
])

@app.callback(dash.dependencies.Output(‘line-plot’, ‘figure’),
[dash.dependencies.Input(‘page-1-dropdown’, ‘value’)])

def display_page(value):
“”“using numpy [3,10] matrix to plot the line plot in which ‘x axis’ will be the first list from the array and other two will be the ‘Y axis’ from matrix”""

data = [np.random.rand(3, 10) for _ in range(4)]
first_data = data[0]
second__data = data[1]
third_data = data[2]
if value == 'first':
    x_axis = [x for x in first_data[0]]
    y_axis = [y for y in first_data[1:]]
    fig = px.line(x=x_axis, y=y_axis)
    return fig
elif value == 'second' :
    x_axis = [x for x in second__data[0]]
    y_axis = [y for y in second__data[1:]]
    fig = px.line(x=x_axis, y=y_axis)
    return fig
elif value == 'third' :
    x_axis = [x for x in third_data[0]]
    y_axis = [y for y in third_data[1:]]
    fig = px.line(x=x_axis, y=y_axis)
    return fig

if name == ‘main’:
app.run_server(debug=True, port = 8090)

Hi,

You have a few options in my opinion, but to my knowledge you can’t just pass as a parameter to px.line

  1. Create a pandas dataframe from the array (with specific column names) and use it to make fig:
data = np.random.rand(3, 10) 
df = pd.DataFrame(data.transpose(), columns=["x", "y0", "y1"]) 
fig = px.line(df, x="x", y=["y0", "y1"])
  1. Modify the trace name after fig is created:
x_axis = [x for x in first_data[0]]
y_axis = [y for y in first_data[1:]]
fig = px.line(x=x_axis, y=y_axis)

for idx, trace in enumerate(fig["data"]):
     trace["name"] = f"y{idx}" 
  1. Use plotly.graph_objects and its constructors (a bigger change):
import plotly.graph_objects as go

data = np.random.rand(3, 10) 

x_axis = [x for x in data[0]]
y_axis = [y for y in data[1:]]
fig = go.Figure(
     [
        go.Scatter(x=x_axis, y=y, mode="lines", name=f"y{idx}") 
        for idx, y in enumerate(y_axis)
     ],
     layout={"showlegend": True}
)

Hope this helps!