捕捉 matplotlib 警告 [英] Catch matplotlib warning

查看:34
本文介绍了捕捉 matplotlib 警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码(如下所示为一个最小的工作示例,MWE)在绘制颜色条时会产生警告:

I have a code (shown below as a minimal working example, MWE) which produces a warning when plotting a colorbar:

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

我想捕捉此警告,以便不显示.

I want to catch this warning so it is not displayed.

我知道我应该按照这个问题中所述的内容应用一些东西我如何捕捉 numpy 警告,就像它是一个例外(不仅仅是为了测试)?,但我不知道如何做吧.

I know I should apply something along the lines of what is stated in this question How do I catch a numpy warning like it's an exception (not just for testing)?, but I'm not sure how to do it.

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

推荐答案

您可能不希望将此警告作为异常捕获.这将中断函数调用.

You probably don't want to catch this warning as an exception. That will interrupt the function call.

使用warnings 标准库模块来控制警告.

Use the warnings standard library module to control warnings.

您可以使用上下文管理器抑制来自特定函数调用的警告:

You can suppress a warning from a specific function call using a context manager:

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

<小时>

忽略来自 matplotlib 的所有警告:


To ignore all warnings from matplotlib:

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

<小时>

仅忽略来自 matplotlib 的 UserWarnings:


To ignore only UserWarnings from matplotlib:

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

这篇关于捕捉 matplotlib 警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆