Plotly Python:点击两个散点生成临时对比图的实现咨询
实现点击两点生成对比图的解决方案
要实现点击散点图中两个不同点后生成新图展示两点信息,关键是利用FigureWidget的点击事件回调跟踪选中点,当选中两个点时自动生成新图。以下是完整可运行的代码:
import numpy as np import plotly.graph_objects as go # 初始化数据 y = np.random.rand(10) x = np.random.rand(10) names = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'L'] # 创建主散点图 fig = go.FigureWidget() fig.add_trace(go.Scatter( x=x, y=y, name='Base scatter', mode='markers', marker=dict(size=7), customdata=names, hovertemplate= '<b>x:</b> %{x}<br><b>y:</b> %{y}<br><b>Name:</b> %{customdata}<br>' )) fig.update_layout(title='Test') # 存储选中点的列表 selected_points = [] def handle_click(trace, points, state): # 获取点击点的索引、坐标和名称 point_idx = points.point_inds[0] point_data = { 'x': x[point_idx], 'y': y[point_idx], 'name': names[point_idx] } # 避免重复选中同一个点 if point_data not in selected_points: selected_points.append(point_data) # 当选中两个点时生成新图 if len(selected_points) == 2: # 创建对比图 compare_fig = go.Figure() # 添加两个点的标记与连接线 compare_fig.add_trace(go.Scatter( x=[p['x'] for p in selected_points], y=[p['y'] for p in selected_points], mode='markers+lines', marker=dict(size=12, color=['red', 'blue']), text=[p['name'] for p in selected_points], hovertemplate= '<b>Name:</b> %{text}<br><b>x:</b> %{x}<br><b>y:</b> %{y}<br>' )) # 设置对比图布局 compare_fig.update_layout( title=f"对比: {selected_points[0]['name']} vs {selected_points[1]['name']}", xaxis_title='X值', yaxis_title='Y值' ) compare_fig.show() # 清空选中列表,允许下次选择 selected_points.clear() # 绑定点击事件到散点图轨迹 fig.data[0].on_click(handle_click) # 显示主图 fig.show()
关键说明:
handle_click是核心点击回调函数,通过points.point_inds获取点击点的索引,提取对应坐标与名称数据。- 加入重复点判断逻辑,避免同一个点被多次选中。
- 选中两个点后自动生成新图,用线连接两点并高亮标记,同时清空选中列表以便后续选择。
- 新图的样式(如标记颜色、大小)可根据需求自行调整,也可添加更多对比维度的信息。
内容的提问来源于stack exchange,提问作者Sala
相关产品推荐
相关产品推荐

