1

I have two subplots drawing line charts with weekend being colored as grey. I am trying to distinguish the subplots by giving them legends. However, I am having an issue with ordering the legends of the subplots. I've referred to this post and tried fig.update_layout(legend_traceorder="reversed") to no avail. In the image below, I want to sort the legends by "A" first then "B", not "B" then "A"

img

Here is the reproducible code:

import numpy as np
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots 

rng = pd.date_range('2022-04-09', periods=20, freq='D')
np.random.seed(42)
first_df = pd.DataFrame({ 'Date': rng, 'Val' : np.random.randn(len(rng))}) 
first_df['Type'] = 'A'

second_df = pd.DataFrame({ 'Date': rng, 'Val' : np.random.randn(len(rng))}) 
second_df['Type'] = 'B'

final_df =  pd.concat([first_df,second_df]).sort_values(by = 'Date')
final_df['Is_Weekend'] = np.where((final_df['Date'].dt.weekday == 5), 1, 0 )

A_df = final_df[final_df['Type']=='A']
B_df = final_df[final_df['Type']=='B']

fig = make_subplots(rows=2, cols=1,
                    shared_xaxes=True,
                    specs=[[{"secondary_y": True}],[{"secondary_y": True}]])

fig.add_trace(go.Scatter(x=A_df['Date'], y=A_df['Is_Weekend'],
                         fill = 'tonexty', fillcolor = 'rgba(128,128,128, 0.2)',
                         line_shape = 'hv', line_color = 'rgba(0,0,0,0)',
                         showlegend = False
                        ),
              row = 1, col = 1, secondary_y=True)

fig.update_xaxes(showgrid=False, row=1, col=1)
fig.update_yaxes(range=[-0,0.1], showgrid=False, tickfont_color = 'rgba(0,0,0,0)', secondary_y=True, row=1, col=1)
fig.add_trace(go.Scatter(x=A_df['Date'], 
                         y = A_df['Val'], 
                         line_color = 'orange',
                         mode = 'lines+markers',
                         showlegend = True, name = "A"),
              row=1, col=1,
              secondary_y = False)

fig.add_trace(go.Scatter(x=B_df['Date'], y=B_df['Is_Weekend'],
                         fill = 'tonexty', fillcolor = 'rgba(128,128,128, 0.2)',
                         line_shape = 'hv', line_color = 'rgba(0,0,0,0)',
                         showlegend = False
                        ),
              row=2, col=1, secondary_y=True)

fig.update_xaxes(showgrid=False, row=2, col=1)
fig.update_yaxes(range=[-0,0.1], showgrid=False,  tickfont_color = 'rgba(0,0,0,0)', secondary_y=True, row=2, col=1)
fig.add_trace(go.Scatter(x=B_df['Date'], 
                         y = B_df['Val'], 
                         line_color = 'blue',
                         mode = 'lines+markers',
                         showlegend = True, name = "B"),
              row=2, col=1,
              secondary_y = False)

fig.update_layout(legend_traceorder="reversed")
fig.show()
user9532692
  • 584
  • 7
  • 28

0 Answers0