日期时间值上的 Seaborn 散点图动画

Seaborn scatter plot animation over datetime values

我以为这会很容易,但我现在正在努力几个小时来为我的 seaborn 散点图制作动画,迭代我的日期时间值。

x 和 y 变量是坐标,我想根据 datetime 变量对它们进行动画处理,用它们的“id”着色。

我的数据集是这样的:

df.head(10)
Out[64]: 
                     date    id    x    y  
0 2019-10-09 15:20:01.418  3479  353  118  
1 2019-10-09 15:20:01.418  3477  315   92  
2 2019-10-09 15:20:01.418  3473  351  176     
3 2019-10-09 15:20:01.418  3476  318  176     
4 2019-10-09 15:20:01.418  3386  148  255     
5 2019-10-09 15:20:01.418  3390  146  118     
6 2019-10-09 15:20:01.418  3447  469  167     
7 2019-10-09 15:20:03.898  3476  318  178     
8 2019-10-09 15:20:03.898  3479  357  117     
9 2019-10-09 15:20:03.898  3386  144  257     

应该迭代的情节如下所示:

.

下面是一个简单的例子。您可能想要修复轴限制以使过渡更好。

import pandas as pd
import seaborn as sns
import matplotlib.animation 
import matplotlib.pyplot as plt

def animate(date):
    df2 = df.query('date == @date')
    ax = plt.gca()
    ax.clear()
    return sns.scatterplot(data=df2, x='x', y='y', hue='id', ax=ax)

fig, ax = plt.subplots()
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=df.date.unique(), interval=100, repeat=True)
plt.show()

注意。我假设日期是按照帧的顺序排序的

编辑:如果使用 Jupyter notebook,您应该包装动画以显示它。例如参见 [​​=12=].

from matplotlib import animation
from IPython.display import HTML
import matplotlib.pyplot as plt
import seaborn as sns

xmin, xmax = df.x.agg(['min', 'max'])
ymin, ymax = df.y.agg(['min', 'max'])

def animate(date):
    df2 = df.query('date == @date')
    ax = plt.gca()
    ax.clear() # needed only to keep the points of the current frame
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    return sns.scatterplot(data=df2, x='x', y='y', hue='id', ax=ax)
    
fig, ax = plt.subplots()

anim = animation.FuncAnimation(fig, animate, frames=df.date.unique(), interval=100, repeat=True)

HTML(anim.to_html5_video())