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

Jupyter Notebook 绘图框选区域提取数据的简易实现方案咨询

Jupyter Notebook 轻量化交互式区域选点、数据提取+Brushing联动解决方案

推荐搜索关键词

你可以用以下关键词搜索更丰富的定制化方案:

  • ipywidgets matplotlib select region extract data
  • matplotlib seaborn linked brushing jupyter
  • mplcursors select data point jupyter
  • jupyter notebook interactive selection get subset

轻量化实现方案(20行核心代码可跑通)

我们用matplotlib原生回调+seaborn原生语法即可实现,不需要引入bokeh这类重框架,初学者可以直接修改示例代码适配自己的数据集:

前置依赖安装

一行命令安装需要的依赖:
pip install ipywidgets seaborn matplotlib pandas numpy

核心实现代码

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.widgets import RectangleSelector

# 替换为你自己的数据集即可
df = pd.DataFrame({
    'x': np.random.randn(200),
    'y1': np.random.randn(200),
    'y2': np.random.randn(200)*2 + 1
})

# 多子图布局,演示brushing联动效果
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12,4))
# 完全使用seaborn语法绘图,无额外改造成本
sns.scatterplot(data=df, x='x', y='y1', ax=ax1, color='blue', alpha=0.6)
sns.scatterplot(data=df, x='x', y='y2', ax=ax2, color='orange', alpha=0.6)

def on_select(eclick, erelease):
    # 获取框选坐标范围
    x_min, x_max = sorted([eclick.xdata, erelease.xdata])
    y_min, y_max = sorted([eclick.ydata, erelease.ydata])
    # 按选中区域筛选数据
    current_ax = eclick.inaxes
    if current_ax == ax1:
        mask = (df['x'].between(x_min, x_max)) & (df['y1'].between(y_min, y_max))
    else:
        mask = (df['x'].between(x_min, x_max)) & (df['y2'].between(y_min, y_max))
    # 筛选结果存入全局变量,可直接提取用于后续分析
    global selected_df
    selected_df = df[mask]
    print(f"已选中{len(selected_df)}条数据,存储在selected_df变量中")
    # Brushing联动:所有子图同步高亮选中数据
    for ax in [ax1, ax2]:
        # 清除历史高亮
        [p.remove() for p in ax.collections if p.get_label() == 'highlight']
        # 绘制新高亮
        target_y = 'y1' if ax == ax1 else 'y2'
        sns.scatterplot(data=selected_df, x='x', y=target_y, ax=ax, 
                        color='red', s=60, label='highlight', alpha=1)
    fig.canvas.draw()

# 给所有子图绑定框选事件
for ax in [ax1, ax2]:
    RectangleSelector(ax, on_select, useblit=True, button=[1], 
                      minspanx=5, minspany=5, spancoords='pixels', interactive=True)

plt.show()

功能说明

  • 框选操作:鼠标左键按住拖拽即可在任意子图画矩形选中区域
  • 数据提取:选中的数据会自动存入selected_df全局变量,可直接打印、导出或做后续分析
  • 联动高亮(Brushing):在任意一个子图选中的区域,所有子图里对应的数据点都会自动变红高亮
  • Seaborn适配:所有seaborn支持的散点、折线、柱状图都可以适配,仅需要修改回调内的筛选逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:36:01