matplotlib 移动圆动画3D打印

mfuanj7w  于 2023-05-01  发布在  其他
关注(0)|答案(1)|浏览(155)

我正在尝试使用Matplotlib和FuncAnimation()制作一个在3D图中移动的圆的动画。一切工作,除了我没有找到一种方法来删除圆已经绘制在前一帧。这导致圆柱体的形成,因为所有绘制的圆重叠。我只想绘制并查看当前帧中的圆。这是我写的代码:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import mpl_toolkits.mplot3d.art3d as art3d
from matplotlib.patches import Circle

fig = plt.figure(figsize = (8, 8))
ax = fig.add_subplot(projection="3d")

ax.set_xlabel('X(t)')
ax.set_ylabel('Y(t)')
ax.set_zlabel('Z(t)')

x_min = -100.
x_max = 100.
y_min = -100.
y_max = 100. 
z_min = -100.
z_max = 100.

ax.set_xlim3d([x_min, x_max])
ax.set_ylim3d([y_min, y_max])
ax.set_zlim3d([z_min, z_max])

x = 0.
y = 0.
# Center of the circle
center = (x, y)

# Values of z along which the circle will move
z = np.arange(0, 100, 1.)

# Initialize the circle in the 3D plot
def init():
    circle = Circle(xy = center, radius = 20., color = "coral")
    ax.add_patch(circle)
    art3d.pathpatch_2d_to_3d(circle, z = z[0], zdir="z")
    return circle

# Animation that changes the z value
def animate(iframe):
    circle = Circle(xy = center, radius = 20., color = "coral")
    ax.add_patch(circle)
    art3d.pathpatch_2d_to_3d(circle, z = z[iframe], zdir="z")
    return circle

anim = animation.FuncAnimation(fig, animate, init_func = init, frames=len(z), interval=100, blit=False, repeat = False)

有办法解决吗?谢谢。

**更新:**如果在animate()的末尾添加:

plt.pause(0.1)
circle.remove()

但是,它不工作,如果plt。不使用pause()。它什么也不做,它不画任何圆圈。

p8h8hvxi

p8h8hvxi1#

你可以在animate函数的开头使用ax.patches.pop()来删除前面的圆(参见here)。
根据您的代码,这将给予:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import mpl_toolkits.mplot3d.art3d as art3d
from matplotlib.patches import Circle

fig = plt.figure(figsize = (8, 8))
ax = fig.add_subplot(projection="3d")

ax.set_xlabel('X(t)')
ax.set_ylabel('Y(t)')
ax.set_zlabel('Z(t)')

x_min = -100.
x_max = 100.
y_min = -100.
y_max = 100. 
z_min = -100.
z_max = 100.

ax.set_xlim3d([x_min, x_max])
ax.set_ylim3d([y_min, y_max])
ax.set_zlim3d([z_min, z_max])

x = 0.
y = 0.
# Center of the circle
center = (x, y)

# Values of z along which the circle will move
z = np.arange(0, 100, 1.)
circle = Circle(xy = center, radius = 0., color = "coral") #Create empty circle that acts as a placeholder
ax.add_patch(circle)
art3d.pathpatch_2d_to_3d(circle, z = z[0], zdir="z")

# Animation that changes the z value
def animate(iframe):
    ax.patches.pop() #remove previous circle
    circle = Circle(xy = center, radius = 20., color = "coral")
    ax.add_patch(circle)
    art3d.pathpatch_2d_to_3d(circle, z = z[iframe], zdir="z")
    return circle

anim = animation.FuncAnimation(fig, animate,frames=len(z), interval=100, blit=False, repeat = False)

相关问题