Matplotlib pyplot show() 关闭后不再工作

7 投票
5 回答
11844 浏览
提问于 2025-04-16 12:45

我有一个这样的循环:

#!/usr/bin/env python
import matplotlib.pyplot as p

for i in xrange(N):
    # Create my_image here

    # Display this image
    p.figure()
    p.imshow(my_image)
    p.show()
    p.close()

当i等于0时,这个循环运行得很好。为了让程序继续下去,我需要关闭由pyplot创建的新图形。对于所有其他的循环迭代(i大于0),不会再创建新的图形,也不会显示图表,程序就直接继续了。为什么关闭一个图形会导致pyplot无法再打开新的图形(就像MATLAB那样)?

我期望的行为是:

  1. 执行在p.show()处暂停
  2. 当我关闭图形时,执行继续
  3. 当再次遇到p.show()时,新的图像会显示出来。
  4. 重复第2步,直到没有更多的图表可以显示

5 个回答

0

在玩弄unutbu的例子后,我发现了一种行为,我可以在PyDev中正常调试,并且可以逐步看到图表的变化。

import time, threading
import numpy
from matplotlib.pyplot import *

x = numpy.linspace(0, 10)
y = x**2

def main():
    plot(x, x)
    draw()
    time.sleep(2)
    plot(x, y)
    draw()

thread = threading.Thread()
thread.run = main

manager = get_current_fig_manager()
manager.window.after(100, thread.start)
figure(1)
show()
5

可能有更好的方法来制作 imshow 的动画,但这个方法在紧急情况下也能用。它是对文档中一个动画示例的轻微修改版本。

# For detailed comments on animation and the techniqes used here, see
# the wiki entry http://www.scipy.org/Cookbook/Matplotlib/Animations

import matplotlib
matplotlib.use('TkAgg')

import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.cm as cm

import sys
import numpy as np
import time

ax = plt.subplot(111)
canvas = ax.figure.canvas

delta=0.025
x=y= np.arange(-3.0, 3.0, delta)
x,y=np.meshgrid(x, y)
z1=mlab.bivariate_normal(x, y, 1.0, 1.0, 0.0, 0.0)
z2=mlab.bivariate_normal(x, y, 1.5, 0.5, 1, 1)
z=z2-z1  # difference of Gaussians

def run(z):
    fig=plt.gcf()
    for i in range(10):
        plt.imshow(z, interpolation='bilinear', cmap=cm.gray,
                  origin='lower', extent=[-3,3,-3,3])
        canvas.draw()
        plt.clf()
        z**=2

manager = plt.get_current_fig_manager()
manager.window.after(100, run, z)
plt.show()
3

这可能是之前版本的matplotlib里面的一个bug。我之前也遇到过类似的问题,当我连续使用show()命令时,只有第一个能显示出来(并且保持在屏幕上);不过,当我把matplotlib更新到1.0.1版本后,这个问题就解决了。

撰写回答