The figure.data name of a trace does not display for a single trace

Hello,

I have a function building the core.Graph figure for me and I noticed that the trace name does only appear in the legend if I have several traces. How can I enforce this even for a single trace?

Here’s the function and caller for context:

def get_graph_figure_from(df):
    figure = {
        'data': [],
        'layout': { 'plot_bgcolor': 'rgb(229,236,246)' }
    }

    df_group_by = df.groupby('deviceName')
    for trace in df_group_by.groups:
        name = ' '.join(trace.split(' ')[-2:])
        trace_data = {
            'x': df_group_by.get_group(trace).loc[:, 'sensorReadingTimestamp'],
            'y': df_group_by.get_group(trace).loc[:, 'temperature'],
            'name': name,
            'mode': 'lines'
        }
        figure['data'].append(trace_data)
    return figure

graph = core.Graph( figure=get_graph_figure_from(temperatures_df))

Thanks

Hi @Benoit you can use the showlegend attribute of the layout of a figure, and/or of traces. For example for a trace created with plotly.graph_objects:

import plotly.graph_objects as go
fig = go.Figure(go.Scatter(x=[1, 2], y=[2, 1]))
fig.update_layout(showlegend=True)
fig.show()

With plotly.express when there is a single trace created its showlegend attribute is set to False so you need to override this like

import plotly.express as px
fig = px.scatter(x=[1, 2], y=[2, 1])
fig.update_traces(showlegend=True, name='trace')
fig.show()

Hello Emmanuelle,

The bad news is, even if the documentation says the default value is True, I had already tried both the showlegend options both in the figure’s data and layout without success.
The good one is I tried again before answering you just to be 200% sure and it worked. I think I used {'showlegend': 'true'} instead of {'showlegend': True} forgetting that I was writing Python :sweat_smile:

It looks better now than the display is consistent across all scenarios

Thanks