首先,(雖然這將不會改變的性能)考慮清理你的代碼,與此類似:
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