优雅地退出 matplotlib.pyplot 动画

2024-10-01 11:21:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,可以绘制一些光度学光圈的数据,我想用xy图来绘制它们。我正在使用matplotlib.pyplot使用Python2.5。在

输入数据存储在大约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回溯错误要优雅得多)?在


Tags: 文件数据方法代码from脚本datamatplotlib
1条回答
网友
1楼 · 发布于 2024-10-01 11:21:59

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

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)中没有必要这样做。在

相关问题 更多 >