用两帧动画 matplotlib 散点图

Animate a matplotlib scatterplot with two frames

我有一个 df 由每个观察的两个不同帧组成,由变量中的结尾字符表示

     name x1 y1 x2 y2
0    bob  3  2  1  4
1    amy  2  1  4  3
2    pam  6  3  3  1
3    joe  4  2  6  5

我想知道如何创建由两帧 ([x1,y1],[x2,y2]) 组成的动画。我看过有关如何使用折线图和条形图创建动画的资源,但找不到太多有关散点图动画的信息。

this question 的回复对我的申请来说似乎有点复杂。

我尝试过的事情:

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

fig = plt.figure(figsize=(5,5))
scatter=ax.scatter(df["x1"], df["y1"])

def animate():
    scatter.set_data(df[['x2','y2'])

我的数据框是否为此正确设置?我还想对这些要点进行注释,但我知道如何使用 adjustText 包进行注释,所以这不是问题,对吧?我假设我不必像设置数据那样设置注释。

感谢任何帮助。谢谢!

linked question 中的答案提到,为了更改散点图的数据,您需要这样做

scatter.set_offsets(array)

从那里或通过阅读 docs/other 资源需要注意的其他一些事情是 animate 函数需要一个参数,即您所在的当前帧。你还应该 return 作为一个元组你想要动画的艺术家。所以至少它应该如下所示:

def animate(i):
    scatter.set_offsets(<the respective (4, 2) array for ith frame>)
    return scatter,

如果你想在你的动画中包含注释,你还必须 return 那些艺术家。在这种情况下,我建议将所有内容都放在一个元组中并通过索引访问它们。这是您的两个框架的简单示例+每个点各自名称的注释:

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

df = pd.DataFrame(
     [['bob', 3, 2, 1, 4], ['amy', 2, 1, 4, 3], ['pam', 6, 3, 3, 1], ['joe', 4, 2, 6, 5]],
     columns=['name', 'x1', 'y1', 'x2', 'y2'])

def animate(i):
     columns = df.columns[1:]
     data = df[columns[2*i:2*i+2]].to_numpy()
     # You can also do `scatter.set_offsets()` and `zip(annnotations, data)`
     artists[0].set_offsets(data)
     for ann, (x, y) in zip(artists[1:], data):
          ann.set_x(x)
          ann.set_y(y)
     return artists,

fig = plt.figure(figsize=(5,5))
scatter = plt.scatter([], [])   # whatever, it'll change every frame
annotations = tuple(plt.annotate(df['name'].iloc[i], (0, 0)) for i in range(len(df)))
artists = (scatter,) + annotations
# Setting them manually here; all points in all frames should be visible
plt.xlim(0, 7)
plt.ylim(0, 7)
anim = FuncAnimation(fig, animate, frames=2)
plt.show()