栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在matplotlib中使用for循环定义多个要动画的图

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在matplotlib中使用for循环定义多个要动画的图

在下面的解决方案中,我展示了一个更大的示例(还带有 条形图
),可以帮助人们更好地理解在其他情况下应采取的措施。在代码之后,我解释了一些细节并回答了奖金问题。

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
返回所有的人。

奖金问题的答案:

  1. line, = plt.plot([], [])
    将返回的列表的第一个元素分配给
    plt.plot
    veriable
    line
  2. line = plt.plot([], [])
    只需分配整个列表(只有一个元素)。


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/639500.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号