捕获matplotlib警告

10 投票
2 回答
7704 浏览
提问于 2025-04-17 21:07

我有一段代码(下面是一个简单的示例,称为 MWE),在绘制颜色条时会产生一个警告:

/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 "

我想要捕捉这个警告,这样它就不会显示出来。

我知道我应该按照这个问题中提到的方法来做,如何像处理异常一样捕捉numpy警告(不仅仅是为了测试),但我不太确定该怎么做。

这是我的 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()

2 个回答

1

打印警告信息是通过调用 showwarning() 函数来完成的,这个函数可以被重写;默认情况下,这个函数会通过调用 formatwarning() 来格式化消息,而这个格式化函数也可以被自定义实现使用。

你可以重写 showwarning() 方法,让它在发出警告时什么都不做。这个函数在被调用时可以获取到警告的消息和类别,所以你可以检查这些信息,只隐藏来自 matplotlib 的警告。

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

17

你可能不想把这个警告当成异常来处理,因为那样会打断函数的调用。

可以使用warnings这个标准库模块来控制警告信息。

如果想要在某个特定的函数调用中忽略一个警告,可以使用上下文管理器:

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

如果想要忽略来自matplotlib的所有警告,可以这样做:

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

如果只想忽略来自matplotlib的用户警告,可以这样做:

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

撰写回答