我想要10個移動點。我使用了下面的代碼。我正在matplotlib做一些我不太了解的實驗。
from matplotlib import pyplot as plt
import numpy as np
from matplotlib import animation
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
# second option - move the point position at every frame
def update_point(n, x, y, z, point):
point.set_data(np.array([x[n], y[n]]))
point.set_3d_properties(z[n], 'z')
return point
def x(i):
return np.cos(t*i)
for i in range(10):
t=np.arange(0, 2*np.pi, 2*np.pi/100)
y=np.sin(t)
z=t/(2.*np.pi)
point, = ax.plot([x(i)[0]], [y[0]], [z[0]], 'o')
ani=animation.FuncAnimation(fig, update_point, 99, fargs=(x(i), y, z, point))
ax.legend()
ax.set_xlim([-1.5, 1.5])
ax.set_ylim([-1.5, 1.5])
ax.set_zlim([-1.5, 1.5])
plt.show()
我希望如果我轉向x的函式i,那么我將在for回圈中有 10 個點,但什么也沒發生。只有一點在移動。我究竟做錯了什么?
uj5u.com熱心網友回復:
首先,您將影片物件anim放入回圈中,因此不僅point資料而且影片物件都被反復覆寫。為了便于使用,讓我們將資料點放入 numpy 陣列中,其中行代表時間,列代表您想要影片的不同點。然后,我們基于陣列計算x、y和陣列(為了美觀,沿著長度為 的列進行無縫回圈,每列移動以使點均勻分布)并簡單地更新、和資料行方式每個影片步驟。與您的腳本密切相關,如下所示:zt2*pixyz
from matplotlib import pyplot as plt
import numpy as np
from matplotlib import animation
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
num_of_points = 7
num_of_frames = 50
t=np.linspace(0, 2*np.pi, num_of_frames, endpoint=False)[:, None] np.linspace(0, 2*np.pi, num_of_points, endpoint=False)[None, :]
x=np.cos(t)
y=np.sin(t)
z=np.sin(t)*np.cos(t)
points, = ax.plot([], [], [], 'o')
def update_points(n):
points.set_data(np.array([x[n, :], y[n, :]]))
points.set_3d_properties(z[n, :], 'z')
return points,
ax.set_xlim([-1.5, 1.5])
ax.set_ylim([-1.5, 1.5])
ax.set_zlim([-1.5, 1.5])
ani=animation.FuncAnimation(fig, update_points, num_of_frames, interval=10, blit=True, repeat=True)
plt.show()
樣本輸出:

當您選擇影片線圖時(這些是沒有可見線的影片標記,散點圖的結構不同),除非您單獨繪制每個點,否則您不能使用不同的顏色。從好的方面來說,您可以使用 blitting 使影片更快。關于您的代碼的另一點 - 我建議不要使用np.arange(),因為這可能會導致端點出現浮動問題。改用
由于時間資訊是從行號派生的,您也可以忘記t輔助陣列并直接用所需或隨機資料填充x、y和z陣列,如下例所示。但是,對于影片,您必須確保狀態之間的平滑過渡,因此沿軸 0 的增量更改是必不可少的。
...
num_of_points = 4
num_of_frames = 100
#random walk
x = np.random.random((num_of_frames, num_of_points))-0.4
y = np.random.random((num_of_frames, num_of_points))-0.3
z = np.random.random((num_of_frames, num_of_points))-0.5
x[:] = x.cumsum(axis=0)
y[:] = y.cumsum(axis=0)
z[:] = z.cumsum(axis=0)
points, = ax.plot([], [], [], 'o')
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/431323.html
標籤:Python matplotlib 动画 3d
