<P>我会考虑使用^ {CD1>},并将一个^ {< CD2>}附加到第二个y轴上,作为背景颜色而不是形状来指示周末。<p>
<h3>绘图:</h3>
<p><a href="https://i.stack.imgur.com/YNKVU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YNKVU.png" alt="enter image description here"/></a></p>
<p>对于我的系统上下面代码段中的<code>nperiods = 2000</code>,<code>%%timeit</code>返回:</p>
<pre><code>162 ms ± 1.59 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code></pre>
<p>我最初建议使用<code>fig.add_shape()</code>的方法要慢得多:</p>
<pre><code>49.2 s ± 2.18 s per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code></pre>
<h3>完整代码:</h3>
<pre><code># %%timeit
# imports
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import datetime
from plotly.subplots import make_subplots
pd.set_option('display.max_rows', None)
# data sample
cols = ['signal']
nperiods = 2000
np.random.seed(12)
df = pd.DataFrame(np.random.randint(-2, 2, size=(nperiods, len(cols))),
columns=cols)
datelist = pd.date_range(datetime.datetime(2020, 1, 1).strftime('%Y-%m-%d'),periods=nperiods).tolist()
df['date'] = datelist
df = df.set_index(['date'])
df.index = pd.to_datetime(df.index)
df.iloc[0] = 0
df = df.cumsum().reset_index()
df['signal'] = df['signal'] + 100
# %%timeit
df['weekend'] = np.where((df.date.dt.weekday == 5) | (df.date.dt.weekday == 6), 1, 0 )
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(go.Scatter(x=df['date'], y=df.weekend, fill = 'tonexty', showlegend = False), secondary_y=True)
fig.update_traces(line_shape = 'hv',
line_color = 'rgba(0,0,0,0)',
fillcolor = 'rgba(99, 110, 250, 0.2)',
row = 1, col = 1)
fig.update_xaxes(showgrid=False)#, gridwidth=1, gridcolor='rgba(0,0,255,0.1)')
fig.update_layout(yaxis2_range=[-0,0.1], yaxis2_showgrid=False, yaxis2_tickfont_color = 'rgba(0,0,0,0)')
fig.add_trace(go.Scatter(x=df['date'], y = df.signal, line_color = 'blue'), secondary_y = False)
fig.update_layout()
fig.show()
</code></pre>