2016-04-18 57 views
0

我跟隨Speeding up Matplotlib -- Bastibe來測試製作動畫,只更新圖中已更改的內容。我使用MacPorts安裝的Mac OS X 10.11.4,Python 3.4。代碼如下所示:Matplotlib draw_artist(axis.patch)在MacOSX後端失敗

'''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) 

此代碼在Python 3.4 + Qt5Agg後端在Ubuntu 14.04上正常工作。但在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 

任何建議表示讚賞!

回答

2

您需要使用不同的後端。 這些行添加到您的腳本的開始:

import matplotlib 

matplotlib.use('Qt4Agg') 

這給我283個地塊,而fig.canvas.draw()只給26個地塊。

+0

好建議邁克。內核必須重啓,否則matplotlib會抱怨'matplotlib.use('Qt4Agg')'沒有效果,因爲後端已經被選中了。你還需要關閉plot'plt.close()'或者它會掛在那裏。 –

+0

謝謝你。事實上,我知道Qt後端的作品,儘管我仍然想知道原始MacOSX後端有什麼問題。或者我應該問一下,如果使用Qt後端而不是原來的後端有一些優勢? – astroboylrx

相關問題