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

การเพิ่ม Label ให้ Colorbar ของ imshow ใน Matplotlib

ใช้ plt.colorbar() สร้าง Colorbar จาก imshow() แล้วเพิ่ม Label ด้วย cbar.set_label()

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้างข้อมูล 2D 5x5
  3. แสดงภาพด้วย imshow()
  4. สร้าง Colorbar จาก image object
  5. ตั้งค่า Label ด้วย set_label()
  6. แสดงผล

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


import numpy as np
from matplotlib import pyplot as plt

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

data = np.random.rand(5, 5)
im = plt.imshow(data, cmap="copper")

# สร้าง colorbar และตั้ง label
cbar = plt.colorbar(im)
cbar.set_label("Colorbar")

plt.show()

การปรับแต่ง Colorbar เพิ่มเติม


# ตั้งค่า Ticks และ Labels
cbar.set_ticks([0, 0.5, 1])
cbar.set_ticklabels(['Low', 'Medium', 'High'])

# ปรับขนาดและตำแหน่ง
cbar = plt.colorbar(im, shrink=0.8, aspect=20, pad=0.05)

# ปรับ Orientation
cbar = plt.colorbar(im, orientation='horizontal')

ผลลัพธ์

Heatmap 5x5 พร้อม Colorbar ด้านขวาที่มี Label "Colorbar"