定义多个地块与一个动画在matplotlib循环 [英] Defining multiple plots to be animated with a for loop in matplotlib
问题描述
感谢杰克Vanderplas ,我知道如何开始code动画剧情与 matplotlib
。下面是一个示例code:
Thanks to Jake Vanderplas, I know how to start to code an animated plot with matplotlib
. Here is a sample code:
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的:'元组'对象没有属性'轴'
)。
Suppose now I'd like to plot tons of functions (say four here), defined with the help of a loop. I did some voodoo programming, trying to understand how to mimic the comma following line and here is what I got (needless to say that it does not work: AttributeError: 'tuple' object has no attribute '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()
我的一些问题是:我怎样才能使它发挥作用?奖金(大概链接):是之间的线plt.plot([],[])
和行= plt.plot(差别= [] [])
?
Some my question is: how can I make it work? Bonus (probably linked): what is the difference between line, = plt.plot([], [])
and line = plt.plot([], [])
?
感谢
推荐答案
首先,我将张贴您的解决方案,然后一些说明:
First I will post you the solution, then some explanations:
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)]
def init():
for line in lines:
line.set_data([], [])
return lines
def animate(i):
for j,line in enumerate(lines):
line.set_data([0, 2], [10 * j,i])
return lines
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=20, blit=True)
plt.show()
说明:
-
行= plt.plot([],[])
通过指定plt.plot $返回列表的第一个元素C $ c>来的veriable
行
。 -
行= plt.plot([],[])
刚分配整个名单(只有一个元素的)。
line, = plt.plot([], [])
assign the first element of the list returned byplt.plot
to the veriableline
.line = plt.plot([], [])
just assign the whole list (of only one element).
替代行= [plt.plot([],[])[0] _范围内的(N)]
你可以这样做 =行plt.plot(*([[] []] * N))
只有一个绘图命令。我找到的第一个更具可读性,但品味的问题。
Alternative to lines = [plt.plot([], [])[0] for _ in range(N)]
you can do this lines = plt.plot( *([[], []]*N) )
with only one plot command. I found the first more readable but is matter of taste.
这篇关于定义多个地块与一个动画在matplotlib循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!