在下面的解决方案中,我展示了一个更大的示例(还带有 条形图
),可以帮助人们更好地理解在其他情况下应采取的措施。在代码之后,我解释了一些细节并回答了奖金问题。
import matplotlibmatplotlib.use('Qt5Agg') #use Qt5 as backend, comment this line for default backendfrom matplotlib import pyplot as pltfrom matplotlib import animationfig = plt.figure()ax = plt.axes(xlim=(0, 2), ylim=(0, 100))N = 4lines = [plt.plot([], [])[0] for _ in range(N)] #lines to animaterectangles = plt.bar([0.5,1,1.5],[50,40,90],width=0.1) #rectangles to animatepatches = lines + list(rectangles) #things to animatedef init(): #init lines for line in lines: line.set_data([], []) #init rectangles for rectangle in rectangles: rectangle.set_height(0) return patches #return everything that must be updateddef animate(i): #animate lines for j,line in enumerate(lines): line.set_data([0, 2], [10 * j,i]) #animate rectangles for j,rectangle in enumerate(rectangles): rectangle.set_height(i/(j+1)) return patches #return everything that must be updatedanim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=20, blit=True)plt.show()说明
这个想法是绘制所需的内容,然后重用所返回的艺术家(请参阅此处的更多信息)
matplotlib。这是通过首先绘制所需内容的虚拟草图并保留对象
matplotlib为您完成的。然后,在
init和
animate函数上,您可以更新需要设置动画的对象。
请注意,由于
plt.plot([], [])[0]我们只有一位 线艺术家 ,因此我将他们与一起收集
[plt.plot([], [])[0]for _ in range(N)]。另一方面,
plt.bar([0.5,1,1.5],[50,40,90],width=0.1)返回可以为
矩形艺术家 迭代的容器。
list(rectangles)只需将此容器转换为要与串联的列表即可
lines。
我行从矩形分开,因为它们是不同的更新(和不同的艺术家),但
init并
animate返回所有的人。
奖金问题的答案:
line, = plt.plot([], [])
将返回的列表的第一个元素分配给plt.plot
veriableline
。line = plt.plot([], [])
只需分配整个列表(只有一个元素)。



