为Plotly Express添加带文本的可切换垂直矩形按钮(默认关闭)
实现Plotly垂直矩形的显示/隐藏切换按钮(带中间文本)
要实现默认隐藏、点击按钮切换垂直矩形的显示/隐藏,且显示时矩形中间带有文本,你可以通过Plotly的updatemenus配置按钮,同时将矩形和文本标记为同一控制组,以下是完整实现代码:
import plotly.express as px import plotly.graph_objects as go # 1. 创建基础示例图表 df = px.data.stocks() fig = px.line(df, x='date', y='GOOG') # 2. 添加垂直矩形(默认隐藏) vrect = fig.add_vrect( x0='2020-04', x1='2020-09', fillcolor="red", opacity=0.25, visible=False, # 默认隐藏 name="highlight_period" ) # 3. 添加矩形中间的文本(默认隐藏,和矩形联动) annotation = fig.add_annotation( x='2020-06-15', # 矩形时间段的中间日期 y=fig.layout.yaxis.range[1] * 0.5, # 垂直方向居中 text="疫情影响期", showarrow=False, font=dict(size=16, color="darkred"), visible=False, # 默认隐藏 name="highlight_text" ) # 4. 添加切换按钮 fig.update_layout( updatemenus=[ dict( type="buttons", direction="left", buttons=list([ dict( label="显示高亮期", method="restyle", args=[{"visible": [True, True]}], # 同步显示矩形和文本 ), dict( label="隐藏高亮期", method="restyle", args=[{"visible": [False, False]}], # 同步隐藏矩形和文本 ) ]), x=0.1, y=1.15, ) ] ) fig.show()
关键细节说明
- 默认隐藏:通过给
add_vrect和add_annotation添加visible=False参数,确保初始状态下元素不可见 - 联动控制:按钮的
restyle方法通过args同时修改矩形和文本的visible属性,实现同步显示/隐藏 - 文本定位:通过计算Y轴范围的中间值让文本垂直居中;X轴设为矩形覆盖时间段的中间日期,保证水平居中
- 按钮样式:可通过调整
x、y参数改变按钮位置,label自定义按钮显示文本
内容的提问来源于stack exchange,提问作者imad97
相关产品推荐
相关产品推荐

