title: order plotly legend by custom order
body: <p>I have a plotly figure to which I add values from two dataframes, df_a and df_b. I display both dataframes in different subplots, but they share a legend. How can I order the shared legend? The expected order is: [a, b, c, f, g]. Please see below for the current implementation - it seems to pick the order from input data in some way.</p>
  <pre><code>import pandas as pd
  from plotly.subplots import make_subplots
  import plotly.graph_objects as go
  import plotly.express as px
  from plotly.offline import iplot
  
  df_a = pd.DataFrame(columns=[&quot;date&quot;, &quot;a&quot;, &quot;b&quot;, &quot;c&quot;], data=[
      [pd.to_datetime(&quot;31Jan20&quot;), 3, 4, 5],
      [pd.to_datetime(&quot;31Mar20&quot;), 3, 4, 5],
      [pd.to_datetime(&quot;30Jun20&quot;), 3, 4, 5],
  ])
  
  df_b = pd.DataFrame(columns=[&quot;date&quot;, &quot;a&quot;, &quot;g&quot;, &quot;f&quot;], data=[
      [pd.to_datetime(&quot;31Jan20&quot;), 8, 5, 4],
      [pd.to_datetime(&quot;31Mar20&quot;), 3, 4, 5],
      [pd.to_datetime(&quot;30Jun20&quot;), 3, 4, 5],
  ])
  
  buckets = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;f&quot;, &quot;g&quot;]
  
  fig_subplots = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=[&quot;df_a&quot;, &quot;df_b&quot;])
  
  def get_chart(df, buckets, d_legend):
      fig = go.Figure()
      colorscale = px.colors.qualitative.Pastel
      i_color = 0
      unique_dates = [str(dt) for dt in df.date.unique()]
      for bucket in sorted(buckets, reverse=True):
  
          y_values = df[df['variable'] == bucket][&quot;value&quot;].to_list()
          enable_legend_for_bucket = False if bucket in d_legend else True
  
          fig.add_trace(go.Bar(
              name=bucket,
              x=unique_dates,
              y=y_values,
              marker_color=colorscale[i_color],
              legendgroup=bucket,   
              showlegend=enable_legend_for_bucket
  
          ))
  
          if len(y_values) != 0:
              d_legend[bucket] = True # store first time this bucket was populated for legend  
  
          i_color += 1
        
      fig.update_layout(barmode=&quot;stack&quot;)       
      return fig, d_legend
  
  list_df = [df_a.melt(id_vars=&quot;date&quot;), df_b.melt(id_vars=&quot;date&quot;)]
  d_legend = {}
  iRow = 1
  for df in list_df:
      fig, d_legend = get_chart(df, buckets, d_legend)
      
      for el in fig['data']:
          fig_subplots.append_trace(el, iRow, 1)
      iRow += 1
  fig_subplots.update_layout(barmode='stack', legend={'traceorder':'normal'})    
  </code></pre>
  <p><a href="https://i.stack.imgur.com/3TR2Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3TR2Z.png" alt="enter image description here" /></a></p>