我认为这会很容易,但我现在挣扎了几个小时来为我的 seaborn 散点图设置动画,迭代我的日期时间值。
x 和 y 变量是坐标,我想根据日期时间变量为它们设置动画,用它们的“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
应该迭代的图如下所示:
有人可以帮忙吗?深表感谢!
答案 0 :(得分:0)
下面是一个简单的例子。您可能想要修复轴限制以使过渡更好。
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 笔记本,您应该包装动画以显示它。参见示例 this post。
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())