Случайное перемещение точки в пространстве matplotlib
Пишу в jupyter notebook. Координаты создаются. Но нет ни точки, ни ее движения. В чем может быть проблема?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
%matplotlib notebook
def random_unit_vector():
angle = np.random.random() * 2 * np.pi
return np.cos(angle), np.sin(angle), np.cos(angle) + np.sin(angle)
def get_random_walk(num_steps):
locations = np.zeros((3, num_steps))
for i in range(1, num_steps):
next_x, next_y, next_z = random_unit_vector()
locations[0, i] = locations[0, i-1] + next_x
locations[1, i] = locations[1, i-1] + next_y
locations[2, i] = locations[2, i-1] + next_z
return locations
def random_step(num_steps, max_step=0.05):
start_pos = np.random.random(3)
steps = np.random.uniform(-max_step, max_step, size=(num_steps, 3))
return start_pos + np.cumsum(steps, axis=0)
fig = plt.figure()
ax = fig.add_subplot(projection="3d", xlim=(-10, 10), ylim=(-10, 10), zlim=(-10, 10))
step, = plt.plot([], [], [])
num_steps = 50
all_steps = get_random_walk(num_steps)
all_steps = random_step(num_steps)
def update(step_num: int):
loc = all_steps[..., step_num]
step.set_data(loc)
step.set_3d_properties(loc)
return step
anim = FuncAnimation(
fig,
update,
num_steps,
interval=500,
)
plt.show;
Ответы (1 шт):
Автор решения: Stanislav Volodarskiy
→ Ссылка
update перепишите так:
def update(step_num: int):
loc = all_steps[:step_num, ...]
step.set_data(loc[..., :2].T)
step.set_3d_properties(loc[..., 2])
return step
Последнюю строку так:
plt.show()