代码之家  ›  专栏  ›  技术社区  ›  Tom

移动球体动画

  •  0
  • Tom  · 技术社区  · 2 年前

    我想在matplotlib中创建一个移动球体的动画。出于某种原因,它不起作用:

    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits import mplot3d
    from matplotlib import cm
    from matplotlib import animation
    import pandas as pd
    
    
    fig = plt.figure(facecolor='black')
    ax = plt.axes(projection = "3d")
    
    u = np.linspace(0, 2*np.pi, 100)
    v = np.linspace(0, np.pi, 100)
    r = 4
    
    ax.set_xlim(0, 60)
    ax.set_ylim(0, 60)
    ax.set_zlim(0, 60)
    
    x0 = r * np.outer(np.cos(u), np.sin(v)) + 10
    y0 = r * np.outer(np.sin(u), np.sin(v)) + 10
    z0 = r * np.outer(np.ones(np.size(u)), np.cos(v)) + 50
    
    def init():
        ax.plot_surface(x0,y0,z0)
        return fig,
    
    def animate(i):
        ax.plot_surface(x0 + 1, y0 + 1, z0 + 1)
        return fig,
    
    ani = animation. FuncAnimation(fig, animate, init_func = init, frames = 90, interval = 300)
    
    
    plt.show()
    

    在这里,我试图在每次新的迭代中将球体移动(1,1,1),但没有成功。

    1 回复  |  直到 2 年前
        1
  •  1
  •   Davide_sd    2 年前

    你的方法有几个错误:

    1. 在你的 animate 函数在每次迭代中添加一个球体。不幸地 Poly3DCollection 对象(由创建) ax.plot_surface )无法在创建曲面后进行修改,因此要为曲面设置动画,我们需要删除上一次迭代的曲面并添加一个新曲面。
    2. 在动画中,球体没有移动,因为在每次迭代中,您都在与前一个球体相同的位置添加一个新球体。
    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits import mplot3d
    from matplotlib import cm
    from matplotlib import animation
    import pandas as pd
    
    
    fig = plt.figure(facecolor='black')
    ax = plt.axes(projection = "3d")
    
    u = np.linspace(0, 2*np.pi, 100)
    v = np.linspace(0, np.pi, 100)
    r = 4
    
    ax.set_xlim(0, 60)
    ax.set_ylim(0, 60)
    ax.set_zlim(0, 60)
    
    x0 = r * np.outer(np.cos(u), np.sin(v)) + 10
    y0 = r * np.outer(np.sin(u), np.sin(v)) + 10
    z0 = r * np.outer(np.ones(np.size(u)), np.cos(v)) + 50
    
    surface_color = "tab:blue"
    
    def init():
        ax.plot_surface(x0, y0, z0, color=surface_color)
        return fig,
    
    def animate(i):
        # remove previous collections
        ax.collections.clear()
        # add the new sphere
        ax.plot_surface(x0 + i, y0 + i, z0 + i, color=surface_color)
        return fig,
    
    ani = animation. FuncAnimation(fig, animate, init_func = init, frames = 90, interval = 300)
    
    
    plt.show()
    
    推荐文章