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

时间:2017-07-08 21:01:22

标签: python pandas matplotlib plot

我目前正在处理一个数据集,其中包含持续时间约为10秒且采样时间为0.1秒的信号。 我的目标是提取这些数据的特定部分并将其保存到python字典中。相关部分大约需要4秒钟。

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

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

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

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

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

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

    提前感谢您和最好的问候,

    曼努埃尔

1 个答案:

答案 0 :(得分:5)

您可以使用SpanSelector

您基本上只需要添加一行以保存到the matplotlib example

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()

enter image description here