【发布时间】:2022-11-07 00:06:36
【问题描述】:
我有 n 条曲线,我想使用 matplotlib 的 animation 绘制(每条曲线对应一个用健身追踪器或智能手机记录的 gpx 文件)。仅使用一首或两首曲目时效果很好。但是一旦我想使它适应使用 n 曲线,我就迷路了。这是我的代码:
import matplotlib.animation as anim
import matplotlib.pyplot as plt
import numpy as np
tracks = {}
xdata = {}
ydata = {}
# in my case n_tracks would rather correspond to a couple of 100
n_tracks = 2
n_waypts = 100
for ii in range(n_tracks):
# generate fake data
lat_pts = np.linspace(10+ii*1,20+ii*1,n_waypts)
lon_pts = np.linspace(10+ii*1,20+ii*1,n_waypts)
tracks[str(ii)] = np.array( [lat_pts, lon_pts] )
xdata[str(ii)] = []
ydata[str(ii)] = []
fig = plt.figure()
ax1 = fig.add_subplot( 1,1,1, aspect='equal', xlim=(0,30), ylim=(0,30) )
plt_tracks = [ax1.plot([], [], marker=',', linewidth=1)[0] for _ in range(n_tracks)]
plt_lastPos = [ax1.plot([], [], marker='o', linestyle='none')[0] for _ in range(n_tracks)]
def animate(i):
# x and y values to be plotted
for jj in range(n_tracks):
xdata[str(jj)].append( tracks[str(jj)][0,i] )
ydata[str(jj)].append( tracks[str(jj)][1,i] )
# update x and y data
for jj in range(n_tracks):
plt_tracks[jj].set_data( xdata[str(jj)][:], ydata[str(jj)][:] )
plt_lastPos[jj].set_data( xdata[str(jj)][-1], ydata[str(jj)][-1] )
return plt_tracks, plt_lastPos
anim = anim.FuncAnimation( fig, animate, frames=n_waypts, interval=20, blit=True )
plt.show()
字典tracks 包含轨道,对于每个轨道,我们有一个包含经度的数组和一个包含纬度数据的数组。字典xdata 和ydata 用于绘图目的。
我有两个带有绘图对象的列表,plt_tracks 和 plt_lastPos,其中第一个用于连续绘制轨道,后者用于指示最新位置。
错误消息为RuntimeError: The animation function must return a sequence of Artist objects. 所以,我的错误似乎是return 语句,但简单地在末尾添加, 在这里没有帮助。任何关于我所缺少的提示将不胜感激。
【问题讨论】:
标签: python matplotlib animation graph matplotlib-animation