5

I'm struggling to hide the legend for some but not all of the lines in my line plot. Here is what the plot looks like now.

Plot:

enter image description here

Essentially I want to hide the legend for the light grey lines while keeping it in place for the coloured lines.

Here's my code:

import plotly.graph_objects as go

fig = go.Figure()
fig.update_layout(autosize=False, width=800, height=500, template='none')
fig.update_layout(title = 'Title', xaxis_title = 'Games', yaxis_title = 'Profit')

for team in rest_teams:
    fig.add_traces(go.Scatter(x=df['x'], y = df[team], name = team, line = {'color': '#F5F5F5'}))

for team in big_eight:
    line_dict = {'color': cmap[team]}
    fig.add_traces(go.Scatter(x=df['x'], y = df[team], name = team, line = line_dict))

fig.show()

I can update layout with

fig.update_layout(showlegend=False)

which hides the whole thing and isn't optimal. Help would be appreciated.

vestland
  • 55,229
  • 37
  • 187
  • 305
Ravi
  • 69
  • 1
  • 7

1 Answers1

4

If I understand your desired output correctly, you can use showlegend = False for the traces where you've set a grey color with color = #F5F5F5:

for c in cols1:
    fig.add_trace(go.Scatter(x = df.index, y = df[c], line_color = '#F5F5F5',
                  showlegend = False))

And then leave that out for the lines you'd like colors assigned to, and make sure to include name = c in:

for c in cols2:
    fig.add_trace(go.Scatter(x = df.index, y = df[c], 
                  name = c))

Plot:

enter image description here

Complete code:

import plotly.graph_objects as go
import plotly.express as px
import pandas as pd


df = px.data.stocks()
df = df.set_index('date')

fig = go.Figure()

cols1 = df.columns[:2]
cols2 = df.columns[2:]

for c in cols1:
    fig.add_trace(go.Scatter(x = df.index, y = df[c], line_color = '#F5F5F5',
                  showlegend = False))

for c in cols2:
    fig.add_trace(go.Scatter(x = df.index, y = df[c], 
                  name = c))
fig.update_layout(template=template
fig.show()
vestland
  • 55,229
  • 37
  • 187
  • 305