在for循环中创建pyplot图,该图在显示下一个循环之前关闭(其间有一个交互式函数)



我正试图通过遍历每个集合并选择是保留还是拒绝来手动策划数据集。要做到这一点,我想绘制一个数据集,请使用点击模块(https://click.palletsprojects.com/en/7.x/)选择是否保留它,然后绘制下一个数据集并重复。目前,我可以绘制每个集合并选择是否保存它,但问题是每个图都保持在下一个图之上。我需要浏览数千个数据集,所以同时绘制它们是不可行的。

for q in np.arange(0,len(x)):
Thing = Data[x[q]-100:x[q]+400]

Thing2 = Data2[x[q]-100:x[q]+400]

plt.plot(Thing)
plt.plot(Thing2)
plt.show()
if click.confirm('Do you want to save?', default=True):
List.append(x[q])

我看到其他人推荐pyplot.ion或matplotlib动画,但它们似乎都不起作用,可能是因为与";单击";出现输入框。我所想做的就是在下一个情节制作之前关闭每个情节,但事实证明这是不可能的!

提前谢谢。

解决方案必须清除当前图形,并在清除的画布上绘制新图形。有多种方法可以发挥作用,中对此进行了很好的描述

  • 如何更新matplotlib中的绘图

由于您显示了两个图,我首先提供了一个在单个图上工作的解决方案。然后,我将展示一个适用于多行或多列的解决方案。


解决方案

单个

以下解决方案和测试代码用于更新单个图,并组合要保存的数据。

import click
import numpy as np
import matplotlib.pyplot as plt

def single(data, n_splits):
""" Split up a dataset in n splits, and then combine the parts that you want to save.  """
fig, ax = plt.subplots()
results = []
for thing in np.hsplit(data, n_splits):
ax.cla()
ax.plot(thing)
fig.show()
plt.pause(0.0001)
if click.confirm('Do you want to save?', default=True):
results.append(thing)
plt.close(fig=fig)
return np.hstack(results) if results else []

示例代码

if __name__ == '__main__':
# Single data example
data = np.random.randn(1000) * 10
result = single(data, n_splits=2)
fig, ax = plt.subplots()
ax.plot(result)
fig.show()
plt.pause(5)

Double

以下代码用于使用子图同时显示两个不同的图。或者,您可以生成两个图形,并分别绘制不同的图形。

def double(data, n_splits):
""" Split up a dataset in n splits, and then combine the parts that you want to save.  """
fig, axs = plt.subplots(nrows=2, squeeze=True)
results = []
for thing_1, thing_2 in np.hsplit(data, n_splits):
for ax, thing in zip(axs, [thing_1, thing_2]):
ax.cla()
ax.plot(thing)
fig.show()
plt.pause(0.0001)
if click.confirm('Do you want to save?', default=True):
results.append([thing_1, thing_2])
plt.close(fig=fig)
return np.hstack(results) if results else []

示例代码

if __name__ == '__main__':
# Multiple plots example
data = np.random.randn(2, 1000) * 10
results = double(data, n_splits=2)
fig, axs = plt.subplots(nrows=2, squeeze=True)
for result, ax in zip(results, axs):
ax.plot(result)
fig.show()
plt.pause(5)

相关内容

最新更新