首先,(虽然这将不会改变的性能)考虑清理你的代码,与此类似:
import matplotlib.pyplot as plt
import numpy as np
import time
x = np.arange(0, 2*np.pi, 0.01)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
lines = [ax.plot(x, y, style)[0] for ax, style in zip(axes, styles)]
fig.show()
tstart = time.time()
for i in xrange(1, 20):
for j, line in enumerate(lines, start=1):
line.set_ydata(np.sin(j*x + i/10.0))
fig.canvas.draw()
print 'FPS:' , 20/(time.time()-tstart)
通过上面的例子,我得到10fps左右。
只是一个快速的说明,根据您的确切用例,matplotlib可能不是一个好的选择。它面向出版质量数据,而不是实时显示。
但是,有很多事情可以加快这个例子。
有两个主要原因,为什么这是如此缓慢。
1)致电fig.canvas.draw()
重新绘制一切。这是你的瓶颈。在你的情况下,你不需要重新绘制轴边界,刻度标签等东西。
2)在你的情况,有很多的小插图有很多刻度标签。这些需要很长时间才能绘制出来。
这些都可以通过使用blitting来修复。
要有效地进行blitting,您必须使用后端特定的代码。在实践中,如果你真的担心流畅的动画,你通常会将matplotlib图块嵌入到某种GUI工具箱中,无论如何,这并不是什么问题。
然而,如果不了解更多关于你在做什么,我无法帮到你。
尽管如此,还是有一个gui中立的方式,它仍然相当快。
import matplotlib.pyplot as plt
import numpy as np
import time
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
fig.show()
# We need to draw the canvas before we start animating...
fig.canvas.draw()
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]
# Let's capture the background of the figure
backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes]
tstart = time.time()
for i in xrange(1, 2000):
items = enumerate(zip(lines, axes, backgrounds), start=1)
for j, (line, ax, background) in items:
fig.canvas.restore_region(background)
line.set_ydata(np.sin(j*x + i/10.0))
ax.draw_artist(line)
fig.canvas.blit(ax.bbox)
print 'FPS:' , 2000/(time.time()-tstart)
这给了我〜200fps。
为了使这个更方便一点,最近版本的matplotlib中有一个animations
模块。
举个例子:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]
def animate(i):
for j, line in enumerate(lines, start=1):
line.set_ydata(np.sin(j*x + i/10.0))
return lines
# We'd normally specify a reasonable "interval" here...
ani = animation.FuncAnimation(fig, animate, xrange(1, 200),
interval=0, blit=True)
plt.show()
以下可能是相关的:http://stackoverflow.com/questions/5003094/how-can-i-speed-up-an-animation – NPE
@aix - Glumpy只在这个例子中有所帮助,因为他正在处理快速显示图像数据。这在这种情况下不起作用。 –
尝试更改后端。看到我的答案:http://stackoverflow.com/a/30655528/2066079。或关于后端的这个FAQ:http://matplotlib.org/faq/usage_faq.html#what-is-a-backend – dberm22