简体   繁体   English

用两帧动画 matplotlib 散点图

[英]Animate a matplotlib scatterplot with two frames

I have a df consisting of two different frames for each observation, denoted by the ending character in the variable我有一个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

I am wondering how to create an animation consisting of two frames ([x1,y1],[x2,y2]).我想知道如何创建一个包含两个帧([x1,y1],[x2,y2])的 animation。 I have seen resources on how to create animations with line and bar charts, but I couldn't find much info on scatterplot animations.我已经看到有关如何使用折线图和条形图创建动画的资源,但我找不到关于散点图动画的太多信息。

The response to this question seems a bit complicated for my application.对于我的应用程序来说,对这个问题的回答似乎有点复杂。

Things I have tried:我尝试过的事情:

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'])

Is my dataframe set up correctly for this?我的 dataframe 是否为此正确设置? I would also like to annotate these points, but I know how to do that with the adjustText package, so that isn't a problem here, right?我也想注释这些点,但我知道如何使用adjustText package 来做到这一点,所以这不是问题,对吧? I'm assuming I don't have to set the annotations like I have to set the data.我假设我不必像设置数据那样设置注释。

Any help is appreciated.任何帮助表示赞赏。 Thanks!谢谢!

The answer in the linked question mentions that in order to change the data of a scatter plot you do 链接问题中的答案提到,为了更改散点图 plot 的数据,您可以这样做

scatter.set_offsets(array)

A few other things to notice from there, or from reading the docs/other resources, is that the animate function requires an argument, which is the current frame you're on.从那里或从阅读文档/其他资源中需要注意的其他一些事情是, animate function 需要一个参数,即您所在的当前帧。 You're also supposed to return as a tuple the artists you want to animate.您还应该以元组的形式返回您想要制作动画的艺术家。 So at minimum it should look like the following:所以至少它应该如下所示:

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

If you want to include annotations in your animation, you also have to return those artists.如果您想在 animation 中包含注释,您还必须返回这些艺术家。 In that case, I suggest putting everything in a tuple and accessing them by index.在这种情况下,我建议将所有内容放在一个元组中并通过索引访问它们。 Here is a simple example for your two frames + the annotation of each point's respective name:这是您的两个框架的一个简单示例+每个点各自名称的注释:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM