【问题标题】:Python, conflict between matplotlib's animation and dashed linesPython,matplotlib的动画和虚线之间的冲突
【发布时间】: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


    【解决方案1】:

    在 TkAgg 和 Qt4Agg 中,即使完全不使用动画,我也可以重现错误。原因确实是行

    plt.axhline(dashes=[10])
    

    the documentation 我们得知dashes

    set[s] 破折号序列,破折号序列,以点数为单位。如果 seq 为空或 seq = (None, None),则线型将设置为solid。

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

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

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

    一切正常运行。

    【讨论】:

      最近更新 更多