Eric Dubé
Eric Dubé

Reputation: 482

Simple way to animate matplotlib plot without using collections

Is there a simple way to animate a scatterplot in matplotlib, in a similar way to which the plot is created?

I know currently I can do this to create the plot: scatter = ax.scatter([x values], [y values], [z values])

However, every example I find online uses numpy functions to generate its data rather than something external like three lists, leaving me with much difficulty understanding how the data is modified in the method which updates the animation.

Is it possible to give matplotlib an entirely new set of data to plot for each frame? (every point of data will change anyway)

Note: in case there are special considerations for this situation, this is a 3D plot.

Upvotes: 0

Views: 949

Answers (1)

Ed Smith
Ed Smith

Reputation: 13206

The easiest way to animate is to plot in interactive mode, as a minimal(ish) examples with lists,

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
plt.show()

for i in range(1000):
    x =[1,2,3,4,5,6,7,8,9,10]
    y =[5,6+i%10,2,3,13,4,1,2,4-i%10,8]
    z =[2+(i%10)*2.,3,3,3,5,7,9+i%10,11,9+i%10,10]

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

    ax.set_xlim([0.,10.])
    ax.set_ylim([0.,20.])
    ax.set_zlim([0.,20.])

    plt.pause(0.01)
    plt.cla()

A reason to plot using numpy arrays instead of lists is the data is stored as a contiguous block and this speeds up plots (it's easy to convert to an array with xn = np.array(x)). The main reason most examples will use various numpy functions is that it is just easier to provide a self contained demonstration with animation in matplotlib requiring a function which adjusts the collection object. For a great example of a minimum scatter plot animation, see the second example of this.

Upvotes: 1

Related Questions