我可以在每个循环中使用Matplotlib生成并显示不同的图像吗?

问题描述 投票:4回答:1

我是Matplotlib和Python的新手。我主要使用Matlab。目前,我正在使用要在其中运行循环的Python代码。在每个循环中,我将进行一些数据处理,然后根据处理后的数据显示图像。当我进入下一个循环时,我希望关闭先前存储的图像并根据最新数据生成一个新图像。

换句话说,我想要一个与下面的Matlab代码等效的python代码:

x = [1 2 3];

for loop = 1:3

    close all;

    y = loop * x;

    figure(1);

    plot(x,y)

    pause(2)

end

我尝试了以下python代码来实现我的目标:

import numpy as np
import matplotlib
import matplotlib.lib as plt

from array import array
from time import sleep

if __name__ == '__main__':

    x = [1, 2, 3]

    for loop in range(0,3):

        y = numpy.dot(x,loop)

        plt.plot(x,y)

       plt.waitforbuttonpress

    plt.show()

此代码将所有图叠加在同一图中。如果将plt.show()命令放入for循环中,则仅显示第一张图像。因此,我无法在Python中复制Matlab代码。

python matlab matplotlib
1个回答
12
投票

尝试一下:

import numpy
from matplotlib import pyplot as plt

if __name__ == '__main__':
    x = [1, 2, 3]
    plt.ion() # turn on interactive mode
    for loop in range(0,3):
        y = numpy.dot(x, loop)
        plt.figure()
        plt.plot(x,y)
        plt.show()
        _ = input("Press [enter] to continue.")

如果要关闭上一个图,然后显示下一个图:

import numpy
from matplotlib import pyplot as plt
if __name__ == '__main__':
    x = [1, 2, 3]
    plt.ion() # turn on interactive mode, non-blocking `show`
    for loop in range(0,3):
        y = numpy.dot(x, loop)
        plt.figure()   # create a new figure
        plt.plot(x,y)  # plot the figure
        plt.show()     # show the figure, non-blocking
        _ = input("Press [enter] to continue.") # wait for input from the user
        plt.close()    # close the figure to show the next one.

[plt.ion()打开交互式模式,使plt.show无阻塞。

这里是您的matlab代码的副本:

import numpy
import time
from matplotlib import pyplot as plt

if __name__ == '__main__':
    x = [1, 2, 3]
    plt.ion()
    for loop in xrange(1, 4):
        y = numpy.dot(loop, x)
        plt.close()
        plt.figure()
        plt.plot(x,y)
        plt.draw()
        time.sleep(2)
© www.soinside.com 2019 - 2024. All rights reserved.