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

如何利用matplotlib的pick_event选中散点图两点并绘制多条连线

使用Matplotlib的pick_event实现散点图选点并添加连线

核心实现逻辑

  • 维护一个列表存储选中的点,每次触发pick_event时将选中点的坐标加入列表
  • 当列表凑够2个点时,立即在两点间绘制连线,之后可重置列表准备下一次选点
  • 散点图初始化必须开启picker参数,让点具备可选中属性

完整代码示例

import matplotlib.pyplot as plt
import numpy as np

# 全局变量:存储选中点、已绘制的连线
selected_points = []
drawn_lines = []

def handle_pick(event):
    global selected_points, drawn_lines
    # 获取当前选中点的坐标
    target_point = event.artist
    point_x = target_point.get_xdata()[event.ind[0]]
    point_y = target_point.get_ydata()[event.ind[0]]
    
    # 将点加入选中列表,同时标记选中状态(改色)
    selected_points.append((point_x, point_y))
    target_point.set_color('crimson')
    
    # 选中两个点时绘制连线
    if len(selected_points) == 2:
        # 绘制两点间的虚线
        new_line, = plt.plot(
            [selected_points[0][0], selected_points[1][0]],
            [selected_points[0][1], selected_points[1][1]],
            color='royalblue', linestyle='--'
        )
        drawn_lines.append(new_line)
        # 重置选中列表,恢复所有点的初始颜色
        selected_points = []
        scatter.set_color('seagreen')
    
    # 实时更新画布
    plt.draw()

# 生成测试用散点数据
np.random.seed(10)
x_coords = np.random.rand(15)
y_coords = np.random.rand(15)

# 创建画布与散点图,设置picker参数(选中范围,单位像素)
fig, ax = plt.subplots()
scatter = ax.scatter(x_coords, y_coords, color='seagreen', picker=6)

# 绑定pick事件处理函数
fig.canvas.mpl_connect('pick_event', handle_pick)

plt.title('点击两个点添加连线')
plt.show()

关键细节说明

  • picker=6:设置点的可选中范围为6像素,降低点击命中难度
  • event.ind[0]:获取被点击点在散点数组中的索引,从而拿到对应坐标
  • 可根据需求调整选中点的样式(比如放大点尺寸),或者保留选中状态不重置列表
  • drawn_lines列表用于存储所有连线,方便后续批量修改或删除

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:52:49