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

วิธีสร้าง Wireframe Plot 3 มิติ ด้วย Matplotlib ใน Python

บทนำ

Matplotlib เป็นไลบรารี Visualization ยอดนิยม สร้างกราฟ 2D/3D ได้ มี Object-oriented API ใช้งานร่วมกับ Jupyter, Spyder ได้

การติดตั้ง

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 my_fun(x, y):
    return np.sin(np.sqrt(x**4 + y**4))

x = np.linspace(-8, 8, 30)
y = np.linspace(-8, 8, 30)
X, Y = np.meshgrid(x, y)
Z = my_fun(X, Y)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_wireframe(X, Y, Z, color='red')
plt.xlabel('X axis')
plt.ylabel('Y axis')
ax.set_title('A wireframe plot')
plt.show()

คำอธิบาย

  • นำเข้า mplot3d toolkit

  • สร้าง grid ด้วย meshgrid

  • คำนวณ Z จากฟังก์ชัน sine

  • ใช้ plot_wireframe แสดงกราฟเส้นกรอบ 3D