在 python 的 for 循环中更新 matplotlib 图形

Updating matplotlib figures within a for loop in python

我正在尝试移动磁性物体并更新其磁场,然后将其绘制在 for 循环中。我想更新 matplotlib 图形,以便在显示最新图形之前删除最后一个图形(可以看出有延迟)。我希望这只发生在一个 window 中(我可能使用了错误的技术术语)。目前,它每次更新磁场时都会创建一个新图形。我尝试使用 plt.cla()、plt.close() 和 plt.clf() 但没有成功。代码如下。任何帮助将不胜感激

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)```

您想通过调用 plt.ion() 来使用 matplotlib 的交互模式,并在循环中的每一帧后使用 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