Search code examples
pythonpython-3.xnumpymatplotlibmatplotlib-animation

matplotlib throwing ZeroDivisionError when saving an animation


I have the following Python script (with some irrelevant bits removed):

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

#constants
xRange = 50
dx = 0.1
tMax = 50
dt = 0.1
c=1

#init
Nx = int(xRange/dx)
Nt = int(tMax/dt)
t=0
uVals = np.zeros( (Nt, Nx) )
xVals = np.arange(int(-xRange/2), int(xRange/2), dx)

#code that calculates uVals, as a function of x and t

fig, ax = plt.subplots()
line, = ax.plot(xVals, uVals[0])

def animate(i):
    line.set_ydata(uVals[i])
    return line,

ani = animation.FuncAnimation(
    fig, animate, interval=int(dx/1000), blit=True, frames=Nt, save_count=50)
ani.save("temp.mp4")
plt.show()

When I run this code, without ani.save(), it displays the expected animation (a simulation of a PDE). However, when I try to save the animation with ani.save("temp.mp4"), I get the following error:

line 45, in <module>
    ani.save("temp.mp4")
  File "C:\Python36\lib\site-packages\matplotlib\animation.py", line 1077, in save
    fps = 1000. / self._interval
ZeroDivisionError: float division by zero

I have no idea why this is happening, and can't find any information on the problem. Would anyone be able to help?


Solution

  • Your interval is zero. int(dx/1000)=0 when dx<1. Maybe do int(np.ceil(dx/1000)) to round up to avoid setting a zero interval? I'm not sure what your intent is there.