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

รายชื่อ Colormap ที่ใช้ได้ใน plt.cm.get_cmap และ plt.colormaps()

Matplotlib มี Colormap (แผนที่สี) สำเร็จรูปมากมาย สามารถดูรายชื่อทั้งหมดได้ผ่าน plt.colormaps() (Matplotlib 3.5+) หรือ plt.cm.datad.keys() (เวอร์ชันเก่า)

วิธีดูรายชื่อ Colormap ทั้งหมด

import matplotlib.pyplot as plt

# Matplotlib 3.5+
cmaps = plt.colormaps()
print(f"Total colormaps: {len(cmaps)}")
for name in sorted(cmaps):
    print(name)

# หรือเวอร์ชันเก่า
# cmaps = list(plt.cm.datad.keys())
# print(sorted(cmaps))

หมวดหมู่ Colormap หลัก

หมวดหมู่คำอธิบายตัวอย่างเหมาะสำหรับ
Perceptually Uniform Sequentialสีเปลี่ยนแบบสม่ำเสมอ ตีความง่าย ไม่บิดเบือนข้อมูลviridis, plasma, inferno, magma, cividis, turboข้อมูลต่อเนื่อง (Heatmap, Contour, Scientific)
Sequentialสีจากอ่อนไปเข้ม แบบเดิมBlues, Greens, Reds, Oranges, Purples, Greys, BuGn, YlOrRdข้อมูลต่อเนื่อง แสดงความหนาแน่น
Divergingสี 2 ด้าน ตรงกลางเป็นกลาง คุณสมบัติ Zero-centeredRdBu, RdYlBu, BrBG, PiYG, PRGn, RdGy, coolwarm, seismicข้อมูลมีศูนย์กลาง (อุณหภูมิ, ผลต่าง, Correlation)
Cyclicสีวนรอบ ต้น-ปลาย銜接twilight, hsv, twilight_shiftedข้อมูลเวลาที่วนซ้ำ, มุม, Phase
Qualitativeสีแยกหมวดหมู่ ไม่มีลำดับtab10, tab20, Set1, Set2, Set3, Pastel1, Pastel2, Accent, Dark2, PairedCategorical Data, Classification
Miscellaneousอื่นๆflag, prism, ocean, gist_earth, terrain, gnuplot, gnuplot2, CMRmapการแสดงผลเฉพาะทาง

การใช้งาน Colormap

import matplotlib.pyplot as plt
import numpy as np

# 1. ใช้ผ่าน string name (แนะนำ)
plt.imshow(data, cmap='viridis')

# 2. ใช้ผ่าน Colormap Object
cmap = plt.cm.viridis
# หรือ
cmap = plt.get_cmap('viridis')

# 3. Colormap แบบ Reversed (เติม _r)
plt.imshow(data, cmap='viridis_r')

# 4. Discretize Colormap (ทำเป็นสีไม่ต่อเนื่อง)
cmap = plt.get_cmap('viridis', 8)  # 8 ระดับสี

# 5. สร้าง Colormap เอง
from matplotlib.colors import LinearSegmentedColormap
colors = ['darkblue', 'cyan', 'yellow', 'red']
custom_cmap = LinearSegmentedColormap.from_list('custom', colors, N=256)

ตัวอย่างแสดง Colormap ทั้งหมด

import matplotlib.pyplot as plt
import numpy as np

cmaps = plt.colormaps()
n = len(cmaps)
cols = 5
rows = (n + cols - 1) // cols

fig, axes = plt.subplots(rows, cols, figsize=(15, rows * 2))
gradient = np.linspace(0, 1, 256).reshape(1, -1)

for ax, name in zip(axes.flat, sorted(cmaps)):
    ax.imshow(gradient, aspect='auto', cmap=name)
    ax.set_title(name, fontsize=8)
    ax.axis('off')

# ซ่อน Axes เหลือ
for ax in axes.flat[n:]:
    ax.axis('off')

plt.suptitle('All Matplotlib Colormaps', fontsize=16)
plt.tight_layout()
plt.show()

คำแนะนำเลือก Colormap

  • viridis: เริ่มต้นมาตรฐาน (Default) - สม่ำเสมอ สวย สำหรับผู้ตาบอดสี
  • plasma, inferno, magma: คล้าย viridis แต่สีต่างกัน
  • cividis: ออกแบบสำหรับ Color Vision Deficiency (CVD)
  • RdBu, coolwarm: สำหรับ Diverging Data (มีศูนย์กลาง)
  • tab10, tab20: สำหรับ Categorical Data (สูงสุด 10/20 หมวด)
  • หลีกเลี่ยง jet, rainbow, hsv - มีปัญหาการรับรู้สี (Perceptual Issues)