Ken Morison
Ken Morison

Reputation: 85

Updating matplotlib figures within a for loop in python

I am trying to move a magnetic object and update its magnetic field which is then plotted in a for loop. I want to update the matplotlib figures such that the last figure is deleted before the latest one is shown (with delay as can be seen). I want this to happen in one window (I might be using the wrong technical term) only. Currently it creates a new figure every time it updates the magnetic field. I tried using plt.cla(), plt.close(), and plt.clf() without success. The code is given below. Any help will be much appreciated

import matplotlib.pyplot as plt
import numpy as np
from magpylib.source.magnet import Box,Cylinder
from magpylib import Collection, displaySystem

# create magnets
s1 = Box(mag=(0,0,600), dim=(3,3,3), pos=(-4,0,20))

# calculate the grid
xs = np.linspace(-15,10,33)
zs = np.linspace(-5,25,44)
POS = np.array([(x,0,z) for z in zs for x in xs])
X,Z = np.meshgrid(xs,zs)

for i in range(20):
    Bs = s1.getB(POS).reshape(44,33,3)     #B-field
    s1.move((0,0,-1))

    # create figure
    fig = plt.figure(figsize=(5,9))

    # display field in xz-plane using matplotlib
    U,V = Bs[:,:,0], Bs[:,:,2]
    plt.streamplot(X, Z, U, V, color=np.log(U**2+V**2))

    plt.show()
    
    sleep(0.2)```

Upvotes: 1

Views: 427

Answers (1)

Sameeresque
Sameeresque

Reputation: 2602

enter image description here

You want to make use of matplotlib's interactive mode by invoking plt.ion() and clear the axes after every frame in the loop using plt.cla():

import matplotlib.pyplot as plt
import numpy as np
from magpylib.source.magnet import Box,Cylinder
from magpylib import Collection, displaySystem
fig, ax = plt.subplots()
# create magnets
s1 = Box(mag=(0,0,600), dim=(3,3,3), pos=(-4,0,20))

# calculate the grid
xs = np.linspace(-15,10,33)
zs = np.linspace(-5,25,44)
POS = np.array([(x,0,z) for z in zs for x in xs])
X,Z = np.meshgrid(xs,zs)
plt.ion()
plt.show()

img=0
for i in range(20):
    Bs = s1.getB(POS).reshape(44,33,3)     #B-field
    s1.move((0,0,-1))
    U,V = Bs[:,:,0], Bs[:,:,2]
    ax.streamplot(X, Z, U, V, color=np.log(U**2+V**2))    
    plt.gcf().canvas.draw()
    plt.savefig('{}'.format(img))
    plt.pause(0.01)
    plt.clf()
    img=img+1

    

Upvotes: 1

Related Questions