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

ทำให้กราฟ 3D โต้ตอบได้ใน Jupyter Notebook (Python & Matplotlib)


ในบทความนี้ เราจะใช้โค้ดตัวอย่างเพื่อแสดงวิธีทำให้กราฟ 3 มิติเป็นโต้ตอบ (interactive) ได้ใน Jupyter Notebook

ขั้นตอน

  • สร้าง Figure ใหม่ หรือเปิดใช้งาน Figure ที่มีอยู่

  • สร้างตัวแปร fig และ ax ด้วยเมธอด subplots โดยค่าเริ่มต้น nrows และ ncols เป็น 1, projection='3d'

  • หา x, y, z โดยใช้ฟังก์ชัน np.cos และ np.sin

  • วาด Wireframe 3D โดยใช้ x, y, z และ color="red"

  • ตั้งค่าชื่อเรื่องให้แกนปัจจุบัน

  • ใช้ plt.show() เพื่อแสดงกราฟ

ตัวอย่าง

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
u, v = np.mgrid[0:2 * np.pi:30j, 0:np.pi:20j]
x = np.cos(u) * np.sin(v)
y = np.sin(u) * np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="red")
ax.set_title("Sphere")
plt.show()

ผลลัพธ์

ทำให้กราฟ 3D โต้ตอบได้ใน Jupyter Notebook (Python & Matplotlib)