如何在绘图中选择区域(Python)并提取区域中的数据

M. *_*idt 6 python plot matplotlib pandas

我目前正在处理一个数据集,该数据集的持续时间约为10秒,采样时间为0.1秒。我的目标是提取此数据的特定部分并将其保存到python字典中。相关部分约4秒长。

理想情况下,这就是我想做的:

  1. 绘制整个10秒的数据。

  2. 标记信号的相关部分,例如使用边框。

  3. 关闭绘图窗口或按一个按钮后,在边界框中提取数据。

  4. 返回1.并获取新数据。

我看到matplotlib可以绘制补丁并提取补丁中的数据点。创建图后(执行plt.show()命令之后)是否可以在图上添加补丁?

预先谢谢您,并致以最诚挚的问候,

曼努埃尔

Imp*_*est 8

您可以使用SpanSelector

基本上,您只需要向matplotlib示例添加一行即可保存。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(211)

x = np.arange(0.0, 5.0, 0.01)
y = np.sin(2*np.pi*x) + 0.5*np.random.randn(len(x))

ax.plot(x, y, '-')
ax.set_ylim(-2, 2)
ax.set_title('Press left mouse button and drag to test')

ax2 = fig.add_subplot(212)
line2, = ax2.plot(x, y, '-')


def onselect(xmin, xmax):
    indmin, indmax = np.searchsorted(x, (xmin, xmax))
    indmax = min(len(x) - 1, indmax)

    thisx = x[indmin:indmax]
    thisy = y[indmin:indmax]
    line2.set_data(thisx, thisy)
    ax2.set_xlim(thisx[0], thisx[-1])
    ax2.set_ylim(thisy.min(), thisy.max())
    fig.canvas.draw_idle()

    # save
    np.savetxt("text.out", np.c_[thisx, thisy])

# set useblit True on gtkagg for enhanced performance
span = SpanSelector(ax, onselect, 'horizontal', useblit=True,
                    rectprops=dict(alpha=0.5, facecolor='red'))

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明