Pylab.Ion() in Python 2, Matplotlib 1.1.1 and Updating of the Plot While the Program Runs

pylab.ion() in python 2, matplotlib 1.1.1 and updating of the plot while the program runs

You want the pause function to give the gui framework a chance to re-draw the screen:

import pylab
import time
import random
import matplotlib.pyplot as plt

dat=[0,1]
fig = plt.figure()
ax = fig.add_subplot(111)
Ln, = ax.plot(dat)
ax.set_xlim([0,20])
plt.ion()
plt.show()
for i in range (18):
dat.append(random.uniform(0,1))
Ln.set_ydata(dat)
Ln.set_xdata(range(len(dat)))
plt.pause(1)

print 'done with loop'

You don't need to create a new Line2D object every pass through, you can just update the data in the existing one.

Documentation:

pause(interval)
Pause for *interval* seconds.

If there is an active figure it will be updated and displayed,
and the gui event loop will run during the pause.

If there is no active figure, or if a non-interactive backend
is in use, this executes time.sleep(interval).

This can be used for crude animation. For more complex
animation, see :mod:`matplotlib.animation`.

This function is experimental; its behavior may be changed
or extended in a future release.

A really over-kill method to is to use the matplotlib.animate module. On the flip side, it gives you a nice way to save the data if you want (ripped from my answer to Python- 1 second plots continous presentation).

example, api, tutorial

matplotlib.pyplot/pylab not updating figure while isinteractive(), using ipython -pylab

The second answer to the question you linked provides the answer: call draw() after every plot() to make it appear immediately; for example:

import time
ion()
x = linspace(-1,1,51)
plot(sin(x))
for i in range(10):
plot([sin(i+j) for j in x])
# make it appear immediately
draw()
time.sleep(1)

If that doesn't work... try what they do on this page: http://www.scipy.org/Cookbook/Matplotlib/Animations

import time

ion()

tstart = time.time() # for profiling
x = arange(0,2*pi,0.01) # x-array
line, = plot(x,sin(x))
for i in arange(1,200):
line.set_ydata(sin(x+i/10.0)) # update the data
draw() # redraw the canvas

print 'FPS:' , 200/(time.time()-tstart)

The page mentions that the line.set_ydata() function is the key part.

Python: Update plot instead of creating a new one

I think the function ion and clf could do the trick.

import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
import seaborn as sns

#Constants
J = 1
h = 1
kbT = 1
beta = 1

#Grid
L = 20 #Dimensions
N = L**2 #Total number of grid points

#Initial configuration
spins = 2*np.random.randint(2, size = (L,L))-1

E = []
i = 0

plt.ion()
plt.figure()
plt.show()

while i < 100000:
for i in range(1,N):
i += 1
s = tuple(npr.randint(0, L, 2)) # Random initial coordinate

# x and y coordinate
(sx, sy) = s
# Periodic boundary condition
sl = (sx-1, sy)
sr = ((sx+1)%L, sy)
sb = (sx, sy-1)
st = (sx, (sy+1)%L)
# Energy
E = spins[s] * ( spins[sl] + spins[sr] + spins[sb] + spins[st] )
if E <= 0 : # If negative, flip
spins[s] *= -1
else:
x = np.exp(-E/kbT) # If positve, check condition
q = npr.rand()
if x > q:
spins[s] *= -1
# Plot (heatmap)
plt.clf()
sns.heatmap(spins, cmap = 'magma')
plt.pause(10e-10)

With the function ion you are making interactive the plot, so you need to:

  • Make it interactive
  • Show the plot
  • Clear the plot in your cycle

Here the reference for the ion function.

Reference for clf is here

Matplotlib: Is there a way so that we can see and work with plot result while the routines after the `.show()` is being processed by Python?

You could use a combination of a separate python process (via multiprocessing) and the blocking behaviour of plt.show() to achieve the desired result:

import matplotlib.pyplot as plt
import time
from multiprocessing import Process

def show_plot(data):
fig, ax = plt.subplots()
ax.plot(data)
plt.show()

def do_calculation():
for i in range(100):
print(i)
time.sleep(0.1)

if __name__ == '__main__':
p = Process(target=show_plot, args=([1,2,3],))
p.start() # start parallel plotting process
do_calculation()
p.join() # the process will terminate once the plot has been closed

Real time matplotlib plot is not working while still in a loop

Here is the solution add this plt.pause(0.0001) in your loop as below:

import matplotlib.pyplot as plt
import time
import random
from collections import deque
import numpy as np

# simulates input from serial port
def random_gen():
while True:
val = random.randint(1,10)
yield val
time.sleep(0.1)

a1 = deque([0]*100)
ax = plt.axes(xlim=(0, 20), ylim=(0, 10))
d = random_gen()

line, = plt.plot(a1)
plt.ion()
plt.ylim([0,10])
plt.show()

for i in range(0,20):
a1.appendleft(next(d))
datatoplot = a1.pop()
line.set_ydata(a1)
plt.draw()
print a1[0]
i += 1
time.sleep(0.1)
plt.pause(0.0001) #add this it will be OK.

Dynamically updating a graphed line in python

You need to call plt.pause in your loop to give the gui a chance to process all of the events you have given it to process. If you do not it can get backed up and never show you your graph.

# get new values and re-plot
plt.ion() # make show non-blocking
plt.show() # show the figure
while True:
print "!"
XX = inteprolate(u,XX)
line.set_xdata(XX[:,0])
line.set_ydata(XX[:,1])
plt.draw() # re-draw the figure
plt.pause(.1) # give the gui time to process the draw events

If you want to do animations, you really should learn how to use the animation module. See this awesome tutorial to get started.

Python- 1 second plots continous presentation

A simple method is to use plt.pause(1). A more sophisticated method is to usethe matplotlib.animate module. See pylab.ion() in python 2, matplotlib 1.1.1 and updating of the plot while the program runs

example, api, tutorial



Related Topics



Leave a reply



Submit