如何使用 matplotlib 实时绘制更新的 numpy ndarray?

How do I plot an updating numpy ndarray in real time using matplotlib?

我有一个 numpy 数组,我使用 np.zeros 在循环外初始化了它。 该数组使用 for 循环内的某个函数进行更新。我希望绘制数组,因为它随着每次迭代而变化。

我在这里看到的大部分答案都是针对列表而不是 ndarray。 我看过以下链接。其中一些我曾尝试修改以达到我的目的,但无济于事。

How to update a plot in matplotlib?

https://github.com/stsievert/python-drawnow/blob/master/drawnow/drawnow.py @Scott Sievert,我也看到了你的代码。但不幸的是,我一直无法弄清楚如何修改它。

Real-time plotting using matplotlib and kivy in Python

Real-time plotting using matplotlib and kivy in Python

https://realpython.com/python-matplotlib-guide/

https://gist.github.com/vaclavcadek/66c9c61a1fac30150514a665c4bcb5dc

http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/

所以基本上我想实时查看 ndarray y 的值。 (见下方代码)

我运行它是一个脚本。@Scott Staniewicz

from numpy.random import random_sample
from numpy import arange, zeros
x = arange(0, 10)
y = zeros((10, 1))
for i in range(10):
    y[i] = sin(random_sample())

免责声明:我很确定我的答案不是最优的,但这是我现在可以做到的。

修改@Scott (Scott Sievert) answer and using his drawnow Github package I have put together this answer. I didn't install drawnow Github package。相反,我只是将 drawnow.py 复制到我的文件夹中。 (这是因为我没有找到任何通过 conda 安装它的方法。我不想不使用 PyPi)

from numpy.random import random_sample
from numpy import arange, zeros
from math import sin
from drawnow import drawnow
from matplotlib import use
from matplotlib.pyplot import figure, axes, ion
from matplotlib import rcParams
from matplotlib.pyplot import style
from matplotlib.pyplot import cla, close
use("TkAgg")
pgf_with_rc_fonts = {"pgf.texsystem": "pdflatex"}
rcParams.update(pgf_with_rc_fonts)
style.use('seaborn-whitegrid')

max_iter = 10**(3)  # 10**(5)  # 10**(2)
y = zeros((max_iter, 1))


def draw_fig():
    # can be arbitrarily complex; just to draw a figure
    # figure() # don't call!
    scott_ax = axes()
    scott_ax.plot(x, y, '-g', label='label')
    # cla()
    # close(scott_fig)
    # show() # don't call!


scott_fig = figure()  # call here instead!
ion()
# figure()  # call here instead!
# ion()    # enable interactivity
x = arange(0, max_iter)
for i in range(max_iter):
    # cla()
    # close(scott_fig)
    y[i] = sin(random_sample())
    drawnow(draw_fig)

最基本的版本看起来像

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 10)
y = np.zeros((10, 1))

fig = plt.figure()
line, = plt.plot(x,y)
plt.ylim(-0.2,1.2)

for i in range(10):
    y[i] = np.sin(np.random.random_sample())
    line.set_data(x[:i+1], y[:i+1])
    plt.pause(1)

plt.show()