我正在尝试根据数据框中的数据制作箭袋图的动画
我在pandas DataFrame中存储了这样的数据,有点像这样
QuivXLoc QuivYLoc QuivXVal QuivYVal QuivColorVal QuivPlotNum
0 -70.22 -127.241 1.624 -0.879 1.846623 1
1 -61.74 -127.241 -0.973 -0.027 0.973375 1
2 -65.98 -121.835 0.046 2.416 2.416438 1
3 -74.46 -121.835 -0.151 2.673 2.677262 1
4 -78.70 -116.429 1.073 -0.954 1.435773 2
我目前正在这样绘制它,它会为每个序列号完美地生成单独的图。
for seq in quidf['QuivPlotNum'].unique():
temp=quidf[quidf['QuivPlotNum']==seq] ## make subset to plot
plt.quiver(temp['QuivXLoc'], temp['QuivYLoc'], temp['QuivXVal'], temp['QuivYVal'], # data
temp['QuivColorVal'], # colour the arrows based on this array
cmap=cm.jet, # colour map
headlength=3) # length of the arrows
还有一些额外的代码来格式化我遗漏的情节。
我想要做的是基于迭代数据框中的序列号来为序列设置动画。我在Quiver Animation中看到的所有示例都涉及通过一些递增的标量来缩放先前的函数。
我想生成的类似箭袋动画的示例,我已经尝试但无法弄清楚如何更改update_quiver以适用于我的应用程序: Plotting animated quivers in Python
答案 0 :(得分:4)
使用matplotlib.animation
模块及其FuncAnimation
类:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
import pandas as pd
# read in the date and group it by the frame number
data = pd.read_csv('data2.csv', index_col=0)
grouped = data.groupby('QuivPlotNum')
# set up the figure
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_xlim(-200, 200)
ax.set_ylim(-200, 200)
# create empty plot for the update function to manipulate
plot = ax.quiver([], [], [], [], [], cmap='jet', headlength=3)
# create an iterator over the group, next() will return a tuple
# of QuivPlotNum, DataFrame
iterator = iter(grouped)
def update(i):
# get next thing in the iterator
key, data = next(iterator)
# set new x, y coordinates for the plot
plot.set_offsets(np.column_stack([data.QuivXLoc, data.QuivYLoc]))
# update vector and color values
plot.set_UVC(data.QuivXVal, data.QuivYVal, data.QuivColorVal)
# create the animation, update every 1000 ms
ani = FuncAnimation(fig, update, interval=1000)
# show it
plt.show()