2014-03-06 91 views
6

我有一個代碼(以下示爲最小的工作實施例,MWE)繪製彩條時會產生一個警告:捕捉matplotlib警告

/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py:1533: UserWarning: This figure includes Axes that are not compatible with tight_layout, so its results might be incorrect. 
    warnings.warn("This figure includes Axes that are not " 

欲捕獲這個警告,因此不顯示它。

我知道我應該沿着How do I catch a numpy warning like it's an exception (not just for testing)?這個問題陳述的內容應用一些東西,但我不知道該怎麼做。

這裏的MWE

import matplotlib.pyplot as plt 
import numpy as np 
import matplotlib.gridspec as gridspec 

x = np.random.randn(60) 
y = np.random.randn(60) 
z = [np.random.random() for _ in range(60)] 

fig = plt.figure() 
gs = gridspec.GridSpec(1, 2) 

ax0 = plt.subplot(gs[0, 0]) 
plt.scatter(x, y, s=20) 

ax1 = plt.subplot(gs[0, 1]) 
cm = plt.cm.get_cmap('RdYlBu_r') 
plt.scatter(x, y, s=20 ,c=z, cmap=cm) 
cbaxes = fig.add_axes([0.6, 0.12, 0.1, 0.02]) 
plt.colorbar(cax=cbaxes, ticks=[0.,1], orientation='horizontal') 

fig.tight_layout() 
plt.show() 

回答

10

你可能不希望趕上這個警告是一個例外。這會中斷函數調用。使用warnings標準庫模塊來控制警告。

可以從特定的函數調用使用上下文經理抑制警告:

import warnings 
with warnings.catch_warnings(): 
    warnings.simplefilter("ignore") 
    fig.tight_layout() 

忽略來自matplotlib所有警告:

warnings.filterwarnings("ignore", module="matplotlib") 

只忽略UserWarni從matplotlib ngs:

warnings.filterwarnings("ignore", category=UserWarning, module="matplotlib") 
+0

這正是我最終使用brycepg,謝謝你添加你的答案! – Gabriel

1

警告消息的印刷是通過調用showwarning(), 其可以被重寫進行;此函數的默認實現 通過調用formatwarning()來格式化消息,這也是可供自定義實現使用的 。

覆蓋showwarning()方法在發出警告時不執行任何操作。該功能在被呼叫時具有可用警告的消息和類別,因此您可以檢查並僅隱藏matplotlib中的警告。

來源:http://docs.python.org/2/library/warnings.html#warnings.showwarning

+0

埃裏克:不知道我將如何覆蓋它,你可以使用MWE創建一個例子嗎?我嘗試在'fig.tight_layout()'上面寫'warnings.filterwarnings(「ignore」)',它可以工作,但我不確定這是否過分。謝謝。 – Gabriel