Plotly中点击标记图例时,如何让箭头随标记一同隐藏?
实现点击图例时箭头随标记一同隐藏的方法
可以通过**绑定图例组(legendgroup)**实现注释箭头与标记的联动显示/隐藏,具体修改如下:
- 给Scatter轨迹添加
legendgroup参数,指定一个统一的分组名称 - 给注释(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
相关产品推荐
相关产品推荐

