感谢Jake Vanderplas, 我知道如何使用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' 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()
我的问题是:如何使它工作?奖励(可能有关联):在line, = plt.plot([], [])
和line = plt.plot([], [])
之间的区别是什么?
谢谢
plt.plot
列表的第一个元素是什么吗? - cjorssenplt.plot
返回一个matplotlib.artist.Artist
对象列表,因此当您绘制一条线时,它将返回仅包含一个元素的列表:即一个matplotlib.lines.Line2D
对象。但是,如果您像这样绘制多条线lines = plt.plot( *([[], []]*N) )
,它将返回所有线条的列表。 - Alvaro Fuentesanimate
的return
中,line
后面的逗号是否是必须的?如果我理解正确你的解决方案,是没有这样的逗号的。 - cjorssenlines
对象,但是如果我想要更新一个lines
和image
对象(比如更新一个点的位置,和更新动画中的matshow()
数组),那会发生什么呢?我能把这两者放在同一个元组里面吗? - Marses