Python Plotly:订购线路子图的传说

发布于 2025-02-13 14:04:10 字数 2874 浏览 1 评论 0原文

我有两个子图绘制线图,周末颜色为灰色。我试图通过给出传说来区分子图。但是,我在订购子图的传奇方面有一个问题。我已经提到此帖子和尝试的图。 update_layout(legend_traceOrder =“ reversed”)无用。 我想按“

在下图中, “ nofollow noreferrer”> “

这是可重复的代码:

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()

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()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文