2013-03-30 41 views
50

我需要在文件中創建一個圖形而不在IPython筆記本中顯示它。在這方面,我不清楚IPythonmatplotlib.pylab之間的相互作用。但是,當我撥打pylab.savefig("test.png")時,除了保存在test.png之外,還會顯示當前數字。在自動創建大量繪圖文件時,這通常是不可取的。或者在需要另一個應用程序進行外部處理的中間文件的情況下。在ipython中調用pylab.savefig而不顯示

不確定這是否是matplotlibIPython筆記本問題。

回答

79

這是一個matplotlib問題,您可以通過使用不向用戶顯示的後端來解決此問題,例如, 「AGG的」:

import matplotlib 
matplotlib.use('Agg') 
import matplotlib.pyplot as plt 

plt.plot([1,2,3]) 
plt.savefig('/tmp/test.png') 

編輯:如果你不想失去顯示地塊的能力,關閉Interactive Mode,只有打電話plt.show()當您準備好顯示圖:

import matplotlib.pyplot as plt 

# Turn interactive plotting off 
plt.ioff() 

# Create a new figure, plot into it, then close it so it never gets displayed 
fig = plt.figure() 
plt.plot([1,2,3]) 
plt.savefig('/tmp/test0.png') 
plt.close(fig) 

# Create a new figure, plot into it, then don't close it so it does get displayed 
plt.figure() 
plt.plot([1,3,2]) 
plt.savefig('/tmp/test1.png') 

# Display all "open" (non-closed) figures 
plt.show() 
+2

好的 - 但是,我想通常保留在iPython內的內聯繪圖。如果在後端完成一個完整的開關,你的建議工作正常。問題在於,如何考慮內聯圖的一般情況以及保存圖的特殊情況(不顯示內聯)。有了您的建議,我試圖重新加載模塊並暫時更改後端,但沒有成功。有關如何暫時更換iPython筆記本會話內後端的任何想法? – tnt

+1

我已經更新了這個問題,以討論交互式繪圖和'close()'和'show()'命令,它們可以解決您的問題。正如您發現的那樣,不支持即時更改後端。 – staticfloat

+3

非常感謝您的反饋。似乎plt.close(fig)是我需要的關鍵命令。我仍然不清楚它是否會影響手術。但是,我可能錯過了一些東西。再次感謝。 – tnt

25

我們不需要plt.ioff()plt.show()(如果我們使用%matplotlib inline)。您可以在沒有plt.ioff()的情況下測試上述代碼。 plt.close()有至關重要的作用。試試這個:

%matplotlib inline 
import pylab as plt 

# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes. 
## plt.ioff() 

# Create a new figure, plot into it, then close it so it never gets displayed 
fig = plt.figure() 
plt.plot([1,2,3]) 
plt.savefig('test0.png') 
plt.close(fig) 

# Create a new figure, plot into it, then don't close it so it does get displayed 
fig2 = plt.figure() 
plt.plot([1,3,2]) 
plt.savefig('test1.png') 

如果您在此的IPython的代碼,它會顯示一個第二的情節,如果你添加plt.close(fig2)到它結束時,你會看到什麼。

總之,如果通過plt.close(fig)密切的身影,它不會被顯示出來。

+0

更好的解決方案! – PlagTag

+0

確實是更好的解決方案!我在一個循環中生成並保存了很多圖。通過'plt.ioff',我得到'RuntimeWarning:超過20個數字已經打開......'。 'plt.close'解決了它。 – Nagasaki45