【问题标题】:matplotlib throwing ZeroDivisionError when saving an animationmatplotlib 在保存动画时抛出 ZeroDivisionError
【发布时间】:2021-08-25 17:59:43
【问题描述】:

我有以下 Python 脚本(删除了一些不相关的部分):

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()

当我在没有ani.save() 的情况下运行此代码时,它会显示预期的动画(PDE 的模拟)。但是,当我尝试使用 ani.save("temp.mp4") 保存动画时,出现以下错误:

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

我不知道为什么会发生这种情况,也找不到有关此问题的任何信息。有人可以帮忙吗?

【问题讨论】:

    标签: python python-3.x numpy matplotlib matplotlib-animation


    【解决方案1】:

    您的间隔为零。 int(dx/1000)=0dx&lt;1。也许int(np.ceil(dx/1000)) 进行四舍五入以避免设置零间隔?我不确定你的意图是什么。

    【讨论】:

    • 非常感谢,不知道在盯着我的代码 10 分钟后我是怎么错过的。 int() 是一个错误,我养成了将浮点数转换为整数的习惯,以防止 range() 函数出错,并且出于某种原因也将其添加到此处。
    猜你喜欢
    • 2018-12-31
    • 2018-11-09
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 2014-07-14
    • 2018-12-15
    • 1970-01-01
    相关资源
    最近更新 更多