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

Plotly中点击标记图例时,如何让箭头随标记一同隐藏?

实现点击图例时箭头随标记一同隐藏的方法

可以通过**绑定图例组(legendgroup)**实现注释箭头与标记的联动显示/隐藏,具体修改如下:

  1. 给Scatter轨迹添加legendgroup参数,指定一个统一的分组名称
  2. 给注释(annotation)同样添加legendgroup参数,使用和轨迹完全相同的分组名称

修改后的完整代码:

import plotly.graph_objects as go
import numpy as np  # 补充原代码缺失的numpy导入

fig = go.Figure()
x = np.array([0,1,2,3])
x_s = np.array([0,1,2,3])
y = np.array([1,1,2,3])
y_s = np.array([0,0,0,0])
fig.add_trace(go.Scatter(
  x=x_s,
  y=y_s,
  name='Test',
  legendgroup="test_group",  # 给标记轨迹分配图例组
  marker=dict(
    size=10,
    cmax=1,
    cmin=0,
    color='black',
    colorscale="Rainbow_r",
    symbol='circle'
  ),
  showlegend=True,
  hoverinfo='text',
  hoverlabel=dict(bgcolor="white", font_color="black"),
  mode='markers',
  textposition="top center"))
fig.add_annotation(
  x=0,
  y=1,
  ax=0,
  ay=0,
  xref='x',
  yref='y',
  axref='x',
  ayref='y',
  text='xxxx',
  showarrow=True,
  arrowhead=3,
  arrowsize=1,
  arrowwidth=1,
  arrowcolor='black',
  legendgroup="test_group"  # 将箭头注释绑定到同一图例组
))

fig.show()

原理说明

Plotly的legendgroup参数可将多个元素(轨迹、注释)归为同一分组,点击图例中的分组名称时,该分组下的所有元素会同步切换显示/隐藏状态,从而实现箭头随标记一同隐藏的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:37:28