การสร้าง Colorbar เดียวที่ใช้ร่วมกับหลาย Subplot (shared colorbar) ใน Matplotlib ทำได้โดยสร้าง Axes แยกสำหรับ Colorbar แล้วใช้ fig.colorbar() กับ mappable object (เช่นภาพจาก imshow)
ขั้นตอนการทำงาน
- นำเข้า
numpyและmatplotlib.pyplot - สร้างข้อมูลสุ่ม 2 มิติ
- สร้าง Figure และ Axes ด้วย
plt.subplots() - แสดงภาพด้วย
ax.imshow(data)และเก็บออบเจกต์ที่คืนมา (im) - สร้าง Axes ใหม่สำหรับ Colorbar ด้วย
fig.add_axes([left, bottom, width, height]) - สร้าง Colorbar ด้วย
fig.colorbar(im, cax=cax) - แสดงผลด้วย
plt.show()
ตัวอย่างโค้ด
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.rand(4, 4)
fig, ax = plt.subplots(nrows=1, ncols=1)
im = ax.imshow(data)
# [left, bottom, width, height] ในพิกัด Figure (0-1)
cax = fig.add_axes([0.9, 0.1, 0.03, 0.8])
fig.colorbar(im, cax=cax)
plt.show()
วิธีสร้าง Shared Colorbar สำหรับหลาย Subplots
fig, axes = plt.subplots(2, 2, figsize=(8, 8))
data_list = [np.random.rand(10, 10) for _ in range(4)]
# ใช้ vmin/vmax เดียวกันทั้งหมด
vmin, vmax = 0, 1
ims = []
for ax, data in zip(axes.flat, data_list):
im = ax.imshow(data, vmin=vmin, vmax=vmax, cmap='viridis')
ims.append(im)
# สร้าง colorbar เดียวด้านขวา
cax = fig.add_axes([0.92, 0.15, 0.02, 0.7])
fig.colorbar(ims[0], cax=cax, label='Intensity')
plt.show()
ทางเลือกง่ายกว่า: ใช้ plt.colorbar() แบบอัตโนมัติ
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
for ax, data in zip(axes, data_list[:3]):
im = ax.imshow(data, cmap='viridis')
# colorbar สำหรับ subplot สุดท้าย แต่อ้างอิง vmin/vmax เดียวกัน
fig.colorbar(im, ax=axes, shrink=0.6, label='Shared Colorbar')
plt.show()
คำอธิบายพารามิเตอร์ colorbar
cax- Axes ที่กำหนดเองสำหรับ colorbarax- Axes หรือ list of axes ที่ colorbar จะเชื่อมโยงshrink- ขนาด colorbar เทียบกับ axes (0-1)aspect- อัตราส่วนความยาว/ความกว้างlabel- ป้ายกำกับ colorbar
การประยุกต์ใช้
เหมาะสำหรับการเปรียบเทียบหลายกราฟที่ใช้สเกลสีเดียวกัน เช่น การแสดงผลโมเดลหลายรัน การวิเคราะห์เวลาช่วงต่างๆ หรือแดชบอร์ดวิทยาศาสตร์