您可以使用字典来创建矩形形状和矩形注释,然后将它们用作 button 的参数。一些细节:我们对按钮使用 "relayout" 方法,因为切换形状和文本注释意味着我们只更改布局,并且 args 和 args2 告诉按钮在打开/关闭时如何表现。
import plotly.express as px
fig = px.scatter(
x=['2020-01-30', '2020-04-01', '2020-04-01','2020-09-01'],
y=[3,2,3,2]
)
rectangle_shape = [dict(
type='rect',
x0='2020-04',
x1='2020-09',
xref='x',
y0=0,
y1=1,
yref='y domain',
fillcolor='red',
opacity=0.25
)]
rectangle_annotation = [dict(
showarrow=False,
x='2020-06-15',
y=2.5,
text="Selected Time Period"
)]
fig.update_layout(
updatemenus=[
dict(
type="buttons",
buttons=[
dict(label="Toggle Rectangle",
method="relayout",
args=[{
"shapes": rectangle_shape,
"annotations": rectangle_annotation}],
args2=[{
"shapes": [],
"annotations": []}]),
],
)
]
)
fig.show()