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

การเข้าใจ Annotation Format ใน Seaborn Heatmap

พารามิเตอร์ fmt ใน sns.heatmap() ควบคุมรูปแบบการแสดงค่าบน Heatmap (Annotation) บทความนี้อธิบายการใช้ fmt=".2%" เพื่อแสดงเป็นเปอร์เซ็นต์

ขั้นตอนการสร้าง Heatmap พร้อม Annotation

  1. ตั้งค่าขนาด Figure
  2. สร้าง DataFrame ด้วยข้อมูลสุ่ม
  3. วาด Heatmap ด้วย annot=True และกำหนด fmt
  4. แสดงผล

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

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
.1eScientific notation1.0e+00
dInteger1

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


# เปลี่ยนสี 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 ด้านข้าง