【问题标题】:matplotlib 3D scatter animationmatplotlib 3D 散点动画
【发布时间】:2021-10-21 06:34:37
【问题描述】:
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(100)
y = np.arange(100)
for t in range(100):
    z = np.ones(100)*t
fig = plt.figure(dpi=1200)
ax = fig.add_subplot(projection='3d')
ax.scatter(x,y,z)

我想根据t 绘制动画情节。例如,当 t = 0 时首先绘制(x[0], y[0], z)。然后在 t = 1 时绘制(x[1], y[1],z),等等。但是,一旦新点显示,以前的点就会消失。请问我该如何实现那请?谢谢你。 另外,如果我将ax.scatter 更改为ax.plot_surface,我将如何实现相同的效果?谢谢。

【问题讨论】:

    标签: python matplotlib animation plot visualization


    【解决方案1】:

    为了播放动画,我重新构建了您的代码。
    首先,您需要定义一个函数update,您想要从一帧更改为下一帧的内容将被更新。在我们的例子中,在update 函数中,我根据t 参数更新xyz 坐标。然后我清除以前的图并用更新的坐标绘制一个新的图。最后,设置坐标轴范围很方便,以保持动画帧固定。

    def update(t):
        ax.cla()
    
        x = np.cos(t/10)
        y = np.sin(t/10)
        z = 5
    
        ax.scatter(x, y, z, s = 100, marker = 'o')
    
        ax.set_xlim(-2, 2)
        ax.set_ylim(-2, 2)
        ax.set_zlim(-1, 10)
    

    然后创建一个图形和一个FuncAnimation 实例,将播放动画的图形、update 函数和其他重要参数传递给该实例,如帧数、它们之间的间隔等.请参阅documentation 了解更多信息。

    fig = plt.figure(dpi=100)
    ax = fig.add_subplot(projection='3d')
    
    ani = FuncAnimation(fig = fig, func = update, frames = 100, interval = 100)
    
    plt.show()
    

    完整代码

    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.animation import FuncAnimation
    
    
    def update(t):
        ax.cla()
    
        x = np.cos(t/10)
        y = np.sin(t/10)
        z = 5
    
        ax.scatter(x, y, z, s = 100, marker = 'o')
    
        ax.set_xlim(-2, 2)
        ax.set_ylim(-2, 2)
        ax.set_zlim(-1, 10)
    
    
    fig = plt.figure(dpi=100)
    ax = fig.add_subplot(projection='3d')
    
    ani = FuncAnimation(fig = fig, func = update, frames = 100, interval = 100)
    
    plt.show()
    


    如果你还想跟踪粒子轨迹,可以添加XYZ列表来保存粒子坐标:

    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.animation import FuncAnimation
    
    
    X = []
    Y = []
    Z = []
    
    
    def update(t):
        ax.cla()
    
        x = np.cos(t/10)
        y = np.sin(t/10)
        z = t/10
    
        X.append(x)
        Y.append(y)
        Z.append(z)
    
        ax.scatter(x, y, z, s = 100, marker = 'o')
        ax.plot(X, Y, Z)
    
        ax.set_xlim(-2, 2)
        ax.set_ylim(-2, 2)
        ax.set_zlim(-1, 10)
    
    
    fig = plt.figure(dpi=100)
    ax = fig.add_subplot(projection='3d')
    
    ani = FuncAnimation(fig = fig, func = update, frames = 100, interval = 100, repeat = False)
    
    plt.show()
    

    【讨论】:

    • 非常感谢。请问如果 t 是函数本身,它会如何工作?
    • 您应该在update 中实现它。 t 依赖什么? t 是如何逐帧变化的?
    • 哦,我想我明白你现在在说什么了。非常感谢。我自己试试。
    猜你喜欢
    • 2012-07-07
    • 2021-03-05
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 2012-05-09
    • 1970-01-01
    相关资源
    最近更新 更多