我想在 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),但它沒有這樣做。
uj5u.com熱心網友回復:
您的方法有幾個錯誤:
- 在您的
animate函式中,您在每次迭代時添加一個球體。不幸的是,Poly3DCollection物件(由 創建ax.plot_surface)在創建后無法修改,因此要為表面設定影片,我們需要洗掉前一次迭代的表面并添加一個新的。 - 在您的影片中,球體沒有移動,因為在每次迭代中,您都在與前一個相同的位置添加了一個新球體。
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/472004.html
標籤:Python matplotlib 动画片 matplotlib-动画
下一篇:在影片中實作方程的問題
