Python,matplotlib的动画和虚线之间的冲突

时间:2017-05-22 13:08:52

标签: python animation matplotlib

我正在使用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')),则会复制完全相同的错误。对于想要在blit=True中使用FuncAnimation选项的Mac用户,请更改后端是一种解决方法(请参阅here),但由于此错误,我无法实现它。

我发现问题源于在图中添加了虚线轴。也就是说,如果我删除该行

plt.axhline(color='k', dashes=[10], zorder=0)

这两个问题都消失了,没有ValueError。

有没有人知道发生了什么?动画模块是否无法处理虚线?

1 个答案:

答案 0 :(得分:0)

在TkAgg和Qt4Agg中我甚至可以在不使用动画的情况下重现错误。原因确实是行

plt.axhline(dashes=[10])

the documentation我们了解dashes

  

设置[s]破折号序列,破折号序列以点开墨水。如果seq为空或seq =(None,None),则linestyle将设置为solid。

现在,很明显[10]不是" on"的序列,而只是" on"。有效序列至少包含两个数字。

确实,如果我们使用有效序列,例如

plt.axhline(dashes=[10,3])

一切都没有问题。