Matplotlib 对多个艺术家进行 blitting

Chr*_*ris 3 python matplotlib python-3.x

我正在尝试创建一个使用 blitting 的动画 Matplotlib 图表。我想在同一个子图中包含散点图、线图和注释。然而,我发现的所有例子,例如https://matplotlib.org/gallery/animation/bayes_update.html似乎只返回一个艺术家,例如,只是一个线图。(我认为我正确使用了艺术家术语,但可能不是。)

我试图将多个艺术家组合在一起,但这似乎不起作用。例如在下面,情节线不会更新,如果 blit 设置为 True 我得到一个 AttributeError: 'Artists' object has no attribute 'set_animated'

from collections import namedtuple

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

fig, ax = plt.subplots()


Artists = namedtuple('Artists', ('scatter', 'plot'))

artists = Artists(
  ax.scatter([], []),
  ax.plot([], [], animated=True)[0],
  )


def init():
    ax.set_xlim(-1, 1)
    ax.set_ylim(-1, 1)
    return artists,


def update(frame):
    artists.scatter.set_offsets([[0, 0]])
    artists.plot.set_data([0, 1], [0, 1])
    return artists,

ani = FuncAnimation(
  fig=fig,
  func=update,
  init_func=init,
  blit=True)

plt.show()
Run Code Online (Sandbox Code Playgroud)

与多个艺术家进行 blitting 的正确方法是什么?

Imp*_*est 5

FuncAnimation文件说,

func: callable 在每一帧调用的函数。第一个参数将是帧中的下一个值。任何额外的位置参数都可以通过 fargs 参数提供。

所需的签名是:

   def func(frame, *fargs) -> iterable_of_artists:
Run Code Online (Sandbox Code Playgroud)

所以返回类型应该是一个列表、元组或者通常是Artists.

使用时,return artists,您将返回艺术家的可迭代对象的可迭代对象。

所以你可以删除逗号,

return artists
Run Code Online (Sandbox Code Playgroud)

更一般地说,命名元组似乎比它在这里帮助更多,那么为什么不简单地返回一个元组呢?

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()

scatter = ax.scatter([], [])
plot = ax.plot([], [], animated=True)[0]

def init():
    ax.set_xlim(-1, 1)
    ax.set_ylim(-1, 1)
    return scatter, plot


def update(frame):
    scatter.set_offsets([[0, 0]])
    plot.set_data([0, 1], [0, 1])
    return scatter, plot

ani = FuncAnimation(
        fig=fig,
        func=update,
        init_func=init,
        blit=True)

plt.show()
Run Code Online (Sandbox Code Playgroud)