如何抑制 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.