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

问题描述 投票:0回答: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个回答
15
投票

试试这个:

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.