【发布时间】:2024-01-30 10:30:02
【问题描述】:
我正在使用 python 和 matplotlib 创建一个简单的动画。 我的代码如下:
import matplotlib
#matplotlib.use('TkAgg')
from matplotlib import animation as animation
from matplotlib import pyplot as plt
import numpy as np
def w(q): return np.exp(-q**2)
support_q = np.linspace(-10,10,200)
support_q1 = np.linspace(-10,10,30)
list_w = [[w(q-q1) for q in support_q] for q1 in support_q1]
fig = plt.figure()
ax = fig.add_subplot(111, xlabel='q', ylabel='w(q-q\')')
line_w, = ax.plot(support_q, list_w[0])
plt.axhline(dashes=[10], zorder=0)
ax.xaxis.major.locator.set_params(nbins=12)
ax.yaxis.major.locator.set_params(nbins=5)
def animate(i):
line_w.set_ydata(list_w[i])
return line_w,
anim = animation.FuncAnimation(fig, animate, frames=len(support_q1), interval=10, blit=False)
#anim.save('animation.mp4')
plt.show()
代码运行流畅,生成我想要的动画。但是,如果我在显示动画之前包含一个保存命令 anim.save('animation.mp4'),我会收到以下错误代码:
File "/Users/usr1/Library/Python/3.5/lib/python/site-packages/matplotlib/backends/backend_agg.py", line 166, in draw_path
self._renderer.draw_path(gc, path, transform, rgbFace)
ValueError: dashes sequence must have an even number of elements
我使用的是 Mac OS X。如果我尝试将后端更改为 TkAgg(使用 matplotlib.use('TkAgg'))而不是保存动画,则会复制完全相同的错误。对于想要在FuncAnimation(参见here)中使用blit=True 选项的Mac 用户来说,更改后端是一种解决方法,但由于这个错误我无法实现它。
我发现问题源于在绘图中添加了虚线轴。也就是说,如果我删除该行
plt.axhline(color='k', dashes=[10], zorder=0)
两个问题都消失了,也没有 ValueError。
有人知道发生了什么吗?动画模块是不是不能处理虚线?
【问题讨论】:
标签: python animation matplotlib