在matplotlib中定义要使用for循环设置动画的多个绘图
我知道如何开始用matplotlib
. 以下是示例代码:
from matplotlib import pyplot as plt
from matplotlib import animation
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(0, 100))
line, = plt.plot([], [])
def init():
line.set_data([], [])
return line,
def animate(i):
line.set_data([0, 2], [0,i])
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=20, blit=True)
plt.show()
假设现在我想绘制成吨的函数(这里是四个),用
一个循环的帮助。我做了一些巫毒编程,试图了解如何
模仿下面的逗号,这里是我得到的(不用说
不起作用:AttributeError:'tuple'对象没有属性'axes'
)。
from matplotlib import pyplot as plt
from matplotlib import animation
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(0, 100))
line = []
N = 4
for j in range(N):
temp, = plt.plot([], [])
line.append(temp)
line = tuple(line)
def init():
for j in range(N):
line[j].set_data([], [])
return line,
def animate(i):
for j in range(N):
line[j].set_data([0, 2], [10 * j,i])
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=20, blit=True)
plt.show()
*我的问题是:我怎样才能让它工作?奖金(可能有联系):什么
是’line,=plt.绘图([],[])和
行=plt.绘图([],
[])`?
谢谢
-
在下面的解决方案中,我展示了一个更大的示例(还有条形图)
这可能有助于人们更好地理解应该为其他情况做些什么。
在代码之后,我解释了一些细节并回答了奖金问题。import matplotlib matplotlib.use('Qt5Agg') #use Qt5 as backend, comment this line for default backend from matplotlib import pyplot as plt from matplotlib import animation fig = plt.figure() ax = plt.axes(xlim=(0, 2), ylim=(0, 100)) N = 4 lines = [plt.plot([], [])[0] for _ in range(N)] #lines to animate rectangles = plt.bar([0.5,1,1.5],[50,40,90],width=0.1) #rectangles to animate patches = lines + list(rectangles) #things to animate def 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 updated def 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 updated anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=20, blit=True) plt.show()
解释
这样做的目的是绘制出你需要的内容,然后重用这些艺术家(见更多)
这里)由“matplotlib”返回。
这是通过首先绘制一个你想要的虚拟草图并保持对象“matplotlib”为您提供。然后在“init”和“animate”函数上
可以更新需要设置动画的对象。
注意,在plt.绘图([],[])[0]
我们有一个线条艺术家,因此我把它们收集起来[plt.绘图([],[])[0]表示范围(N)]
。另一方面
扁钢([0.5,1,1.5],[50,40,90],width=0.1)
返回可以
为矩形艺术家迭代。list(矩形)
just convert this将容器放入一个要与“行”连接的列表中。
我将线条与矩形分开,因为它们的更新方式不同
(和是不同的艺术家)但是’init’和’animate’返回所有的艺术家。
问题答案:
1行,=plt.绘图([],[])
指定返回的列表的第一个元素plt.绘图
到可验证的“行”。
2直线=plt.绘图([],[])
只需分配整个列表(仅一个元素)。