【问题标题】:Quitting matplotlib.pyplot animation gracefully优雅地退出 matplotlib.pyplot 动画
【发布时间】:2010-12-16 15:53:15
【问题描述】:

我有一个脚本可以绘制一些测光孔径的数据,我想将它们绘制在 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 回溯错误更优雅)?

【问题讨论】:

    标签: python animation quit matplotlib


    【解决方案1】:

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

    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)中没有必要。

    【讨论】:

    • 当我尝试运行您的程序时,绘图会闪烁到屏幕上,并且程序会引发类型错误:NoneType not iterable 因为数据数组中有一些 Nones
    • 对,有一个错字。我已经修复了它,它现在应该可以工作了。
    猜你喜欢
    • 2011-10-20
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 2020-11-10
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    相关资源
    最近更新 更多