python - Matplotlib 传输多个艺术家

标签 python python-3.x matplotlib

我正在尝试创建一个使用 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()

与多个艺术家进行位 block 传输的正确方法是什么?

最佳答案

FuncAnimation文档说

func : callable The function to call at each frame. The first argument will be the next value in frames. Any additional positional arguments can be supplied via the fargs parameter.

The required signature is:

   def func(frame, *fargs) -> iterable_of_artists:

因此返回类型应该是列表、元组或者通常是 Artists 的可迭代对象。

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

所以你可以删除逗号,

return artists
<小时/>

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

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

关于python - Matplotlib 传输多个艺术家,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52899813/

相关文章:

python - 使 tkinter 文本小部件适合窗口

python - 在 Pygame 中检测多边形和矩形之间的碰撞

python - 在matplotlib中的两条垂直线之间填充

python - 如何纠正 ax.annotate 中的坐标移动

python-3.x - 使用 Scikit-learn 将 Kmeans 应用于 3D 数据

python - 透明色图

python - python列中字母的频率

python - 使用 quickfix python 和 twisted

javascript - 上传 CSV 文件并在 Bokeh Web 应用程序中阅读

python - 如何制作自定义 python 站点包?