1

I'm trying to learn how to animate plots using matplotlib's built in funcAnimation class. For this example, I just want to generate a 2D scatter plot of randomly distributed normal values and add a point to the plot (animate the points appearing) each time I update the points. The example code is below:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random

plt.ion()
fig, ax = plt.subplots()
scat = ax.scatter([],[])
scat.axes.axis([-5, 5, -5, 5])

def update(point):
    array = scat.get_offsets()
    array = np.append(array, point)
    scat.set_offsets(array)
    return scat

def data_gen():
    for _ in range(0,100):
        point = np.random.normal(0, 1, 2)
        yield point

ani = animation.FuncAnimation(fig, update, data_gen, interval=25, blit=False)
plt.show()

When I run this code, nothing happens. The terminal churns for a few seconds, and then nothing happens.

I'm using this as my guide: http://matplotlib.org/examples/animation/animate_decay.html, and if I use a line plot instead of a scatter plot (essentially just replacing how the points are generated in the generator of this example) it "works" as far as it generates data and updates the plots. But it is not the display I want, I want to see the point appearing on a scatter plot. To use a scatter plot, I need to not use set_data, as that is not a valid method for scatter plots; so I'm using the np.append() method which I've seen in this example: Dynamically updating plot in matplotlib

So my question is, what am I doing wrong in this code that is causing the animation to not show up?

EDIT: I've just tried/found out that if I add: mywriter = animation.FFMpegWriter(fps=60) ani.save('myanimation.mp4',writer=mywriter) It does produce an mp4 that contains the animation, I just can't get it to dynamically display as the code is running. So please focus on that problem if you are able to diagnose it. Thanks.

Community
  • 1
  • 1
Zach
  • 341
  • 1
  • 3
  • 14
  • Your code works fine for me, if I just delete the line `plt.ion()`. Do you need that for anything? Usually `ion()` is only used when plotting in ipython and I'm not sure if that is what you want. – ImportanceOfBeingErnest Nov 12 '16 at 15:10
  • Thanks! I was just looking at example codes and they all had that; so I thought it was necessary for the animation. That fixed it! – Zach Nov 14 '16 at 14:10

1 Answers1

1

For future reference, @ImportanceOfBeingErnest pointed out that plot.ion() is not necessary and is specific to plotting in ipython. Removing that fixes the problem.

Zach
  • 341
  • 1
  • 3
  • 14