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

วิธีพล็อตจุดกระจาย 3D พร้อม Colorbar ใน Matplotlib


ใช้เมธอด scatter() และ colorbar()

ขั้นตอนการทำงาน

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • สร้าง figure ใหม่หรือเปิดใช้งาน figure ที่มีอยู่ด้วย figure()
  • เพิ่ม axis เป็น subplot arrangement
  • สร้างข้อมูล xs, ys และ zs ด้วย numpy
  • ใช้ scatter() สร้างกราฟกระจาย
  • ใช้ colorbar() พร้อม scatter scalar mappable instance สำหรับ colorbar
  • ใช้เมธอด show() เพื่อแสดงรูปภาพ

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

import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()
ax = fig.add_subplot(projection="3d")
xs = np.random.rand(100)
ys = np.random.rand(100)
zs = np.random.rand(100)
sc = ax.scatter(xs, ys, zs, c=xs, cmap="copper")
plt.colorbar(sc)
plt.show()

ผลลัพธ์

วิธีพล็อตจุดกระจาย 3D พร้อม Colorbar ใน Matplotlib