Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีสร้าง 3D Contour Plot ด้วย Matplotlib ใน Python

บทนำ

3D Contour Plot แสดงเส้นระดับ (Contour lines) ใน 3 มิติ ช่วยมอง gradient descent และหาค่า optimal parameters

การติดตั้ง

pip install matplotlib

Dependencies

Python>=3.4, NumPy, Setuptools, Pyparsing, Libpng, Pytz, FreeType, Six, Cycler, Dateutil

ตัวอย่างโค้ด

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_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
ax.set_title('A sample 3D contour plot')
plt.show()

คำอธิบาย

  • ใช้ contour3D ระบุจำนวนระดับ (50) และ colormap

  • ตั้งค่า label ทุกแกน และ title