You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotly/Python:如何设置图表默认隐藏注释并通过按钮切换

解决Plotly图表默认无注释的问题

要实现默认显示无注释的图表,点击"Label:On"显示注释、"Label:Off"隐藏注释,需要修改以下3个关键点:

  • 初始设置图表注释为空,而非默认添加注释列表
  • 确保按钮的active参数对应默认激活的按钮(这里是"Label:Off",索引为0)
  • 修正visible参数取值(原图表仅1条折线trace,用[True]即可,避免多余元素引发错误)

修改后的完整代码:

import plotly.express as px
import pandas as pd

# 构造数据
data = {'x': ["2022-05-06", "2022-05-08", "2022-05-09", "2022-05-12", "2022-05-15", "2022-05-16", "2022-05-22", "2022-05-24", "2022-05-26"], 
        'y': [0, 1, 8, 2, 4, 3, 4, 6, 5], 
        'text':["","","Annotation1","","Annotation2","","","","Annotation3"]}
  
df = pd.DataFrame(data)

data1 = {'x': ["2022-05-07", "2022-05-14", "2022-05-23"], 
        'text':["Annotation1", "Annotation2", "Annotation3"]}

df1 = pd.DataFrame(data1)

fig = px.line(df, x='x', y='y', title='Annotations ON / OFF')

# 构建注释列表
arrow_list=[]
counter=0
for i in df1['text'].tolist():
  if i != "":
    arrow=dict(x=df1['x'].values[counter],y=9,xref="x",yref="y",text=i,arrowhead = 2,ax=0,
               arrowwidth=1.5,
               bordercolor="#c7c7c7",
               borderwidth=2,
               borderpad=4,
               bgcolor="#ff7f0e",
               opacity=0.8,
            font=dict(
            family="Courier New, monospace",
            size=16,
            color="#ffffff"
            ),
               arrowcolor='rgb(255,51,0)',)
    arrow_list.append(arrow)
    counter+=1
  else:
    counter+=1
    

# 添加按钮控制逻辑
fig.update_layout(
    updatemenus=[
        dict(
            type="buttons",
            active=0,  # 默认激活"Label:Off"按钮
            showactive=True,
            buttons=list([
                dict(label="Label:Off",
                     method="update",
                     args=[{"visible": [True]},  # 保持折线可见
                           {"annotations": []}]),  # 清空注释

                dict(label="Label:On",
                     method="update",
                     args=[{"visible": [True]},  # 保持折线可见
                           {"annotations": arrow_list}]),  # 加载注释
            ]),
        )
    ])

# 初始设置无注释
fig.update_layout(annotations=[])
fig.show()

关键修改说明:

  1. 初始注释设置:将原代码最后一行的fig.update_layout(annotations=arrow_list)改为fig.update_layout(annotations=[]),确保图表加载时默认无注释。
  2. 修正visible参数:原代码中visible列表包含多个布尔值,但图表只有1条折线trace,仅需[True]即可保证折线始终可见,避免无效参数引发的异常。
  3. 按钮状态匹配:active=0对应第一个按钮"Label:Off",初始状态与按钮执行效果一致,保证默认显示逻辑正确。

内容的提问来源于stack exchange,提问作者Essegn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:15:59