asts bins
asts bins

Reputation: 43

How can i make points of a python plot appear over time?

I would like to create a animation where my data points would gradually appear on my graph and freeze when all the data points have appeared. I've seen in done with correlations i'm just not too sure how to do it with just individual points themselves

This isn't something that will show anything particularly useful but i though it would look cool since i am trying to visualize some location data on a map

I know this isn't very clear so please as for clarifications, I'm not too sure how to phrase my problem very well.

Thanks

Upvotes: 4

Views: 16819

Answers (1)

Andrey Sobolev
Andrey Sobolev

Reputation: 12713

matplotlib.animation.FuncAnimation is the right tool for you. First create an empty graph, and then gradually add data points to it in the function. The following piece of code will illustrate it:

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

x = np.arange(10)
y = np.random.random(10)

fig = plt.figure()
plt.xlim(0, 10)
plt.ylim(0, 1)
graph, = plt.plot([], [], 'o')

def animate(i):
    graph.set_data(x[:i+1], y[:i+1])
    return graph

ani = FuncAnimation(fig, animate, frames=10, interval=200)
plt.show()

The result (saved as gif file) is shown below: enter image description here

EDIT: To make the animation look stopped when finished in matplotlib window, you need to make it infinite (omit frames parameter in FuncAnimation), and set the frame counter to the last number in your frame series:

def animate(i):
    if i > 9:
        i = 9
    graph.set_data(x[:i+1], y[:i+1])
    return graph

ani = FuncAnimation(fig, animate, interval=200)

Or, which is better, you can set repeat parameter in FuncAnimation to False, as per answer to this question.

EDIT 2: To animate a scatter plot, you need a whole bunch of other methods. A piece of code is worth a thousand words:

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

x = np.arange(10)
y = np.random.random(10)
size = np.random.randint(150, size=10)
colors = np.random.choice(["r", "g", "b"], size=10)

fig = plt.figure()
plt.xlim(0, 10)
plt.ylim(0, 1)
graph = plt.scatter([], [])

def animate(i):
    graph.set_offsets(np.vstack((x[:i+1], y[:i+1])).T)
    graph.set_sizes(size[:i+1])
    graph.set_facecolors(colors[:i+1])
    return graph

ani = FuncAnimation(fig, animate, repeat=False, interval=200)
plt.show()

Upvotes: 15

Related Questions