如何抑制 Matplotlib 警告?


我们举个例子。我们创建一组数据点,以便生成一些警告。我们将创建 -1 到 1 之间的数据点 x,并尝试找出该范围内的对数,这意味着在计算对数时,它将对值 0 抛出错误。

步骤

  • 使用 numpy 创建 x 的数据点并计算 log(x)。
  • 使用 plot() 方法绘制 x 和 y。
  • 使用 warnings.filterwarnings("ignore") 抑制警告。
  • 要显示图形,请使用 show() 方法。

示例

import numpy as np
from matplotlib import pyplot as plt
import warnings
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
warnings.filterwarnings("ignore")
x = np.linspace(-1, 1, 10)
y = np.log(x)
plt.plot(x, y)
plt.show()

输出

当我们执行代码时,它将抑制警告并显示以下绘图。

现在,删除这一行,warnings.filterwarnings("ignore") 并再次执行代码。它将显示绘图,但带有运行时警告。

RuntimeWarning: invalid value encountered in log

更新时间: 2021-05-07

4K+ 查看次数

开启你的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.