matplotlib 3D scatter animation

Viewed 248
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(100)
y = np.arange(100)
for t in range(100):
    z = np.ones(100)*t
fig = plt.figure(dpi=1200)
ax = fig.add_subplot(projection='3d')
ax.scatter(x,y,z)

I would like to plot in a animation plot depending on t. for example first plot (x[0], y[0], z) when t = 0. And then (x[1], y[1],z) when t = 1, etc. However, the previous points disappear once the new points shows. May I ask how I can achieve that please? Thank you. Also , if I change ax.scatter to ax.plot_surface, how would I achieve the same stuff please? Thanks.

1 Answers

I re-structured your code in order to play the animation.
First of all, you need to define a function update where the things you want to change from one frame to the next will be updated. In our case, in the update function I update x, y and z coordinates based on t parameter. Then I clear the previuos plot and plot a new one with updated coordinates. Finally it is convenient to set axes limits, in order to keep the animation frame fixed.

def update(t):
    ax.cla()

    x = np.cos(t/10)
    y = np.sin(t/10)
    z = 5

    ax.scatter(x, y, z, s = 100, marker = 'o')

    ax.set_xlim(-2, 2)
    ax.set_ylim(-2, 2)
    ax.set_zlim(-1, 10)

Then you create a figure and a FuncAnimation instance, to which you pass the figure over which play the animation, the update function and other important parameters, as the number of frames, the interval between them and so on. Refer to the documentation for more information.

fig = plt.figure(dpi=100)
ax = fig.add_subplot(projection='3d')

ani = FuncAnimation(fig = fig, func = update, frames = 100, interval = 100)

plt.show()

Complete Code

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation


def update(t):
    ax.cla()

    x = np.cos(t/10)
    y = np.sin(t/10)
    z = 5

    ax.scatter(x, y, z, s = 100, marker = 'o')

    ax.set_xlim(-2, 2)
    ax.set_ylim(-2, 2)
    ax.set_zlim(-1, 10)


fig = plt.figure(dpi=100)
ax = fig.add_subplot(projection='3d')

ani = FuncAnimation(fig = fig, func = update, frames = 100, interval = 100)

plt.show()

enter image description here


If you also want to keep track of the particle trajectory, you can add X, Y and Z list in which to save particle coordinates:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation


X = []
Y = []
Z = []


def update(t):
    ax.cla()

    x = np.cos(t/10)
    y = np.sin(t/10)
    z = t/10

    X.append(x)
    Y.append(y)
    Z.append(z)

    ax.scatter(x, y, z, s = 100, marker = 'o')
    ax.plot(X, Y, Z)

    ax.set_xlim(-2, 2)
    ax.set_ylim(-2, 2)
    ax.set_zlim(-1, 10)


fig = plt.figure(dpi=100)
ax = fig.add_subplot(projection='3d')

ani = FuncAnimation(fig = fig, func = update, frames = 100, interval = 100, repeat = False)

plt.show()

enter image description here

Related