如何在 Matplotlib 中繪製掩碼和 NaN 值?


若要在 Matplotlib 中繪製掩碼和 NaN 值,我們可以採取以下步驟 -

  • 設定圖形大小和調整子圖之間及周圍的邊距。
  • 使用 numpy 建立 xy 資料點。
  • 獲取 x2y2 資料點,使得 y > 0.7
  • 獲取掩碼 y3 資料點,使得 y > 0.7
  • y3 掩碼為 NaN 值。
  • 使用 plot() 方法繪製 xyy2y3y4
  • 為繪圖新增圖例。
  • 設定繪圖的標題。
  • 要顯示圖形,請使用 show() 方法。

示例

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(-np.pi/2, np.pi/2, 31)
y = np.cos(x)**3

# 1) remove points where y > 0.7
x2 = x[y <= 0.7]
y2 = y[y <= 0.7]

# 2) mask points where y > 0.7
y3 = np.ma.masked_where(y > 0.7, y)

# 3) set to NaN where y > 0.7
y4 = y.copy()
y4[y3 > 0.7] = np.nan

plt.plot(x*0.1, y, 'o-', color='lightgrey', label='No mask')
plt.plot(x2*0.4, y2, 'o-', label='Points removed')
plt.plot(x*0.7, y3, 'o-', label='Masked values')
plt.plot(x*1.0, y4, 'o-', label='NaN values')
plt.legend()

plt.title('Masked and NaN data')

plt.show()

輸出

更新於:2021-6-10

3K+ 瀏覽次數

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告