【问题标题】:Catch matplotlib warning捕捉 matplotlib 警告
【发布时间】:2014-03-06 14:18:39
【问题描述】:

我有一个代码(在下面显示为一个最小的工作示例,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 "

我想捕捉这个警告,让它不显示。

我知道我应该按照这个问题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()

【问题讨论】:

    标签: python matplotlib warnings


    【解决方案1】:

    您可能不想将此警告视为异常。这将中断函数调用。

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

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

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

    忽略来自 matplotlib 的所有警告:

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

    仅忽略来自 matplotlib 的 UserWarnings:

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

    【讨论】:

    • 这正是我最终使用 brycepg 的结果,感谢您添加答案!
    【解决方案2】:

    警告信息的打印是通过调用 showwarning() 来完成的, 可能会被覆盖;此函数的默认实现 通过调用 formatwarning() 格式化消息,这也是 可供自定义实现使用。

    在发出警告时重写showwarning() 方法以不执行任何操作。该函数在调用时具有可用的警告消息和类别,因此您可以检查并仅隐藏来自matplotlib 的警告。

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

    【讨论】:

    • Eric:不确定我会如何覆盖它,你能用 MWE 创建一个例子吗?我尝试在fig.tight_layout() 上方写warnings.filterwarnings("ignore") 并且它有效,但我不确定这是否是矫枉过正。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多