如何在 Matplotlib 中繪製掩碼和 NaN 值?
若要在 Matplotlib 中繪製掩碼和 NaN 值,我們可以採取以下步驟 -
- 設定圖形大小和調整子圖之間及周圍的邊距。
- 使用 numpy 建立 x 和 y 資料點。
- 獲取 x2 和 y2 資料點,使得 y > 0.7。
- 獲取掩碼 y3 資料點,使得 y > 0.7。
- 將 y3 掩碼為 NaN 值。
- 使用 plot() 方法繪製 x、y、y2、y3 和 y4。
- 為繪圖新增圖例。
- 設定繪圖的標題。
- 要顯示圖形,請使用 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()
輸出
廣告