1

我正在尝试移动磁性物体并更新其磁场,然后将其绘制在 for 循环中。我想更新 matplotlib 数字,以便在显示最新数字之前删除最后一个数字(可以看出有延迟)。我希望这仅在一个窗口中发生(我可能使用了错误的技术术语)。目前,它每次更新磁场时都会创建一个新图形。我尝试使用 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)```
4

1 回答 1

1

在此处输入图像描述

您想通过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

    
于 2020-10-18T03:26:50.830 回答