2

我有一个脚本可以绘制一些测光孔径的数据,我想将它们绘制在 xy 图中。我在 python 2.5 中使用 matplotlib.pyplot。

输入数据存储在大约 500 个文件中并被读取。我知道这不是输入数据的最有效方式,但这是另一个问题......

示例代码:

import matplotlib.pyplot as plt

xcoords = []
ycoords = []

# lists are populated with data from first file

pltline, = plt.plot(xcoords, ycoords, 'rx')

# then loop populating the data from each file

for file in filelist:
    xcoords = [...]
    ycoords = [...]

pltline.set_xdata(xcoords)
pltline.set_ydata(ycoords)
plt.draw()

由于有超过 500 个文件,我偶尔会想在绘图中间关闭动画窗口。我的绘图代码有效,但它并没有非常优雅地退出。绘图窗口对单击关闭按钮没有响应,我必须Ctrl+C退出它。

谁能帮我找到一种在脚本运行时关闭动画窗口的方法,同时看起来很优雅(比一系列 python 回溯错误更优雅)?

4

1 回答 1

2

如果您更新数据并循环绘制,您应该能够中断它。这是一个示例(绘制一个静止的圆圈,然后围绕周边移动一条线):

from pylab import *
import time

data = []   # make the data
for i in range(1000):
    a = .01*pi*i+.0007
    m = -1./tan(a)
    x = arange(-3, 3, .1)
    y = m*x
    data.append((clip(x+cos(a), -3, 3),clip(y+sin(a), -3, 3)))


for x, y in data:  # make a dynamic plot from the data
    try:
        plotdata.set_data(x, y)
    except NameError:
        ion()
        fig = figure()
        plot(cos(arange(0, 2.21*pi, .2)), sin(arange(0, 2.21*pi, .2)))
        plotdata = plot(x, y)[0]
        xlim(-2, 2)
        ylim(-2, 2)
    draw()
    time.sleep(.01)

我输入time.sleep(.01)命令是为了更加确定我可以中断运行,但在我的测试(运行 Linux)中,这不是必需的。

于 2009-11-15T04:31:04.697 回答