พารามิเตอร์ fmt ใน sns.heatmap() ควบคุมรูปแบบการแสดงค่าบน Heatmap (Annotation) บทความนี้อธิบายการใช้ fmt=".2%" เพื่อแสดงเป็นเปอร์เซ็นต์
ขั้นตอนการสร้าง Heatmap พร้อม Annotation
- ตั้งค่าขนาด Figure
- สร้าง DataFrame ด้วยข้อมูลสุ่ม
- วาด Heatmap ด้วย
annot=Trueและกำหนดfmt - แสดงผล
ตัวอย่างโค้ด
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# สร้างข้อมูลสุ่ม 5x5
df = pd.DataFrame(np.random.random((5, 5)),
columns=["a", "b", "c", "d", "e"])
# fmt=".2%" แสดงเป็นเปอร์เซ็นต์ 2 ตำแหน่งทศนิยม
sns.heatmap(df, annot=True, annot_kws={"size": 7}, fmt=".2%")
plt.show()
รูปแบบ fmt ที่ใช้บ่อย
| Format | ความหมาย | ตัวอย่าง |
|---|---|---|
.2f | ทศนิยม 2 ตำแหน่ง | 0.75 |
.2% | เปอร์เซ็นต์ 2 ตำแหน่ง | 75.00% |
.0f | จำนวนเต็ม | 1 |
.1e | Scientific notation | 1.0e+00 |
d | Integer | 1 |
การปรับแต่งเพิ่มเติม
# เปลี่ยนสี Colormap
sns.heatmap(df, annot=True, fmt=".2%", cmap="RdYlBu_r")
# ปรับขนาด Font ของ Annotation
sns.heatmap(df, annot=True, fmt=".2%", annot_kws={"size": 10, "weight": "bold"})
# แสดงเฉพาะบางเซลล์
mask = np.triu(np.ones_like(df, dtype=bool))
sns.heatmap(df, annot=True, fmt=".2%", mask=mask)
ผลลัพธ์
Heatmap 5x5 แสดงค่าเป็นเปอร์เซ็นต์ 2 ตำแหน่งทศนิยม ในแต่ละเซลล์ พร้อม Colorbar ด้านข้าง