我想根据csv文件中的实际时间戳为动画散点图设置动画(见下文)。我对matplotlib不太了解,我知道动画函数和ion() - 函数,但我不知道如何实现它。 我读了this,但似乎很难以我的方式实现它。 我已经尝试了下面的代码,但它只显示每个循环一个带有实际数据的新窗口,但我想在一个窗口中将动画提前感谢:):
import pandas as pd
import matplotlib.pyplot as plt
start_time = 86930.00
end_time = 86934.00
df = pd.read_csv('Data.csv', delimiter=',')
for timestamp in range(int(start_time), int(end_time), 1):
act_data = df.loc[df['timestamp'] == float(timestamp)]
X = act_data.x
Y = act_data.y
plt.scatter(X, Y)
plt.show()
Data.csv:
timestamp,id,x,y
86930.00,1,1155.53,7155.05
86930.00,2,3495.08,8473.46
86931.00,1,3351.04,6402.27
86931.00,3,3510.59,8021.62
86931.00,2,2231.04,6221.27
86931.00,4,3710.59,8111.62
86932.00,2,3333.01,6221.27
86932.00,1,3532.59,3178.62
86933.00,3,1443.01,2323.27
86933.00,4,5332.59,1178.62
如果我可以通过ID对斑点进行着色而不是必要的话,那会很酷。)。
答案 0 :(得分:2)
在同一轴上制作动画的最快方法是使用交互式图表plt.ion
import pandas as pd
import matplotlib.pyplot as plt
start_time = 86930.00
end_time = 86934.00
df = pd.read_csv('Data.csv', delimiter=',')
fig, ax = plt.subplots(1,1)
plt.ion()
plt.show()
for timestamp in range(int(start_time), int(end_time), 1):
act_data = df.loc[df['timestamp'] == float(timestamp)]
X = act_data.x
Y = act_data.y
ax.scatter(X, Y)
plt.pause(1.0)
虽然,我怀疑你的标题中你想要一些互动的东西,你也可以使用matplotlib
slider widget。
有了你的数据,
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
start_time = 86930.00
end_time = 86934.00
df = pd.read_csv('Data.csv', delimiter=',')
fig, ax = plt.subplots(1,1)
plt.subplots_adjust(bottom=0.25)
sax = plt.axes([0.25, 0.1, 0.65, 0.03])
slide = Slider(sax, 'time', start_time, end_time, valinit=start_time)
#Initial plot
act_data = df.loc[df['timestamp'] == float(int(start_time))]
s, = ax.plot(act_data.x, act_data.y, 'o')
def update(timestamp):
act_data = df.loc[df['timestamp'] == float(int(timestamp))]
X = act_data.x
Y = act_data.y
#Update data based on slider
s.set_xdata(X)
s.set_ydata(Y)
#Reset axis limits
ax.set_xlim([X.min()*0.9,X.max()*1.1])
ax.set_ylim([Y.min()*0.9,Y.max()*1.1])
fig.canvas.draw()
slide.on_changed(update)
plt.show()