How Do I Plot An Updating Numpy Ndarray In Real Time Using Matplotlib?
I have a numpy array which I initialized outside the loop using np.zeros. This array is updated using some function inside a for a loop. I wish to plot the array as it changes with
Solution 1:
Disclaimer : I am quite sure my answer is not the most optimal, but this is what I could achieve for now.
Modifying @Scott (Scott Sievert) answer and using his drawnow Github package I have put together this answer. I didn't install drawnow Github package . Instead I just copied drawnow.py into my folder. (This is because I didn't find any way to install it via conda. I didn't wan't to use 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))
defdraw_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 inrange(max_iter):
# cla()# close(scott_fig)
y[i] = sin(random_sample())
drawnow(draw_fig)
Solution 2:
The most basic version would look like
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 inrange(10):
y[i] = np.sin(np.random.random_sample())
line.set_data(x[:i+1], y[:i+1])
plt.pause(1)
plt.show()
Post a Comment for "How Do I Plot An Updating Numpy Ndarray In Real Time Using Matplotlib?"