如何使用 Python 中的 Matplotlib 建立三維等高線圖?
Matplotlib 是一個流行的 Python 包,用於資料視覺化。視覺化資料是一個關鍵步驟,因為它有助於理解資料中正在發生的事情,而無需實際檢視數字並執行復雜的計算。它有助於有效地將定量見解傳達給受眾。
Matplotlib 用於使用資料建立二維圖。它帶有一個面向物件的 API,有助於將繪圖嵌入 Python 應用程式中。Matplotlib 可以與 IPython shell、Jupyter notebook、Spyder IDE 等一起使用。
它用 Python 編寫。它是使用 NumPy 建立的,NumPy 是 Python 中的數值 Python 包。
可以使用以下命令在 Windows 上安裝 Python:
pip install matplotlib
Matplotlib 的依賴項為:
Python ( greater than or equal to version 3.4) NumPy Setuptools Pyparsing Libpng Pytz Free type Six Cycler Dateutil
建立三維圖是為了檢視資料點的 x-、y- 和 z- 軸。它也可用於瞭解梯度下降函式的工作原理,以及為演算法找到係數的最佳值。
讓我們瞭解如何使用 Matplotlib 建立三維等高線圖:
示例
from mpl_toolkits import mplot3d import numpy as np import matplotlib.pyplot as plt def fun(x, y): return np.sin(np.sqrt(x ** 2 + y ** 2)) x = np.linspace(−5, 5, 30) y = np.linspace(−5, 5, 30) X, Y = np.meshgrid(x, y) Z = fun (X, Y) fig = plt.figure() ax = plt.axes(projection='3d') ax.contour3D(X, Y, Z, 50, cmap='binary') ax.set_ylabel("Y−axis") ax.set_xlabel("X−axis") ax.set_zlabel("Z−axis") ax.set_title('A sample 3D contour plot') plt.show()
輸出
解釋
匯入所需的包並定義其別名以方便使用。
建立一個名為“fun”的函式,該函式使用兩個變數使用“sin”函式生成資料。
使用 NumPy 庫建立資料值。
使用“figure”函式建立一個空圖形。
使用“axes”函式建立繪製圖形的軸。
“contour3D”用於指定正在使用已建立的資料視覺化 3 維等高線圖。
使用 set_xlabel、set_ylabel、'z_label' 和 set_title 函式為 X 軸、Y 軸、Z 軸和標題提供標籤。
使用“show”函式在控制檯上顯示。
廣告