Difficulties in plotting an animated 3D scatter plot from results contained in a list
Hello guys!
I'm a beginner in Python and though I can conceptualize the plot I want to make, I'm really struggling to implement it in Python. Basically I want to make a 3-D scatter plot where I represent the movement of particles during 200 iterations where their positions (x,y,z) are changed. I have their movement history stored in a list with size 200 (size = nr of iterations) in which every element of the list is a numpy array with 3 columns (the x, y and z positions).
My objective is to show the trajectory of the particles along with time. But I can't find examples that match my case, and I'm running out of time to implement this solution... ChatGPT isn't helping a lot because I'm probably failing to communicate my problem clearly. This is as far as I got in terms of code, and it just returned an empty 3D plot.
pos_history = optimizer.pos_history # I get the positions (x,y,z) from the optimizer I used summary_results = np.array(pos_history) # I was told to convert the list to a np array but this didn't really solve the issue at hand... fig = plt.figure() ax = fig.add_subplot(111, projection='3d')
Create an empty scatter plot that will be updated in the animation
sc = ax.scatter([], [], [], marker='o')
def update(frame): ax.cla() # Clear the current plot ax.set_xlabel('X Axis') ax.set_ylabel('Y Axis') ax.set_zlabel('Z Axis') ax.set_title(f'Iteration {frame + 1}')
# Extract the data for the current frame
frame_data = summary_results[frame]
x = frame_data[:, 0]
y = frame_data[:, 1]
z = frame_data[:, 2]
# Update the scatter plot
sc = ax.scatter(x, y, z, marker='o')
ani = FuncAnimation(fig, update, frames=len(summary_results), repeat=False, interval=100) plt.show()
Could you guys help me? I'd be forever grateful. Kind regards, and best wishes to you all, Gustavo Rangel