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

วิธีสร้าง Colorbar มาตรฐานสำหรับหลายกราฟใน Python Matplotlib

การสร้าง Colorbar เดียวที่ใช้ร่วมกับหลาย Subplot (shared colorbar) ใน Matplotlib ทำได้โดยสร้าง Axes แยกสำหรับ Colorbar แล้วใช้ fig.colorbar() กับ mappable object (เช่นภาพจาก imshow)

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

  1. นำเข้า numpy และ matplotlib.pyplot
  2. สร้างข้อมูลสุ่ม 2 มิติ
  3. สร้าง Figure และ Axes ด้วย plt.subplots()
  4. แสดงภาพด้วย ax.imshow(data) และเก็บออบเจกต์ที่คืนมา (im)
  5. สร้าง Axes ใหม่สำหรับ Colorbar ด้วย fig.add_axes([left, bottom, width, height])
  6. สร้าง Colorbar ด้วย fig.colorbar(im, cax=cax)
  7. แสดงผลด้วย 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 ที่กำหนดเองสำหรับ colorbar
  • ax - Axes หรือ list of axes ที่ colorbar จะเชื่อมโยง
  • shrink - ขนาด colorbar เทียบกับ axes (0-1)
  • aspect - อัตราส่วนความยาว/ความกว้าง
  • label - ป้ายกำกับ colorbar

การประยุกต์ใช้

เหมาะสำหรับการเปรียบเทียบหลายกราฟที่ใช้สเกลสีเดียวกัน เช่น การแสดงผลโมเดลหลายรัน การวิเคราะห์เวลาช่วงต่างๆ หรือแดชบอร์ดวิทยาศาสตร์