我正在关注Speeding up Matplotlib -- Bastibe测试制作动画,只更新图中已更改的内容。我使用的是Mac OS X 10.11.4,MacPorts安装的Python 3.4。代码如下:
'''Import modules'''
import matplotlib.pyplot as plt
import numpy as np
import time
'''Initialize figure and axis, perform first draw on canvas'''
fig, ax = plt.subplots()
line, = ax.plot(np.random.randn(100))
plt.show(block=False)
fig.canvas.draw()
'''Count how many plots made within 1 second'''
tstart = time.time()
num_plots = 0
while time.time()-tstart < 1: # within 1 second
line.set_ydata(np.random.randn(100)) # update line
ax.draw_artist(ax.patch) # draw background
ax.draw_artist(line) # draw line
fig.canvas.update() # update canvas
fig.canvas.flush_events()
num_plots += 1 # count++
print(num_plots)
此代码在Ubuntu 14.04上使用Python 3.4 + Qt5Agg后端正常工作。但在Mac上,它会报告
Traceback (most recent call last):
File "./test.py", line 19, in <module>
ax.draw_artist(ax.patch)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/axes/_base.py", line 2340, in draw_artist
a.draw(self._cachedRenderer)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/artist.py", line 61, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/patches.py", line 486, in draw
gc = renderer.new_gc()
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/backends/backend_macosx.py", line 99, in new_gc
self.gc.save()
RuntimeError: CGContextRef is NULL
任何建议都表示赞赏!
答案 0 :(得分:2)
您需要使用不同的后端。 将这些行添加到脚本的最开头:
import matplotlib
matplotlib.use('Qt4Agg')
这给了我283个图,而fig.canvas.draw()
只给出了26个图。