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

การเพิ่มขอบกำหนดเองให้เซลล์บางส่วนใน Matplotlib/Seaborn Heatmap

ใช้ sns.clustermap() สร้าง heatmap แล้วเข้าถึง axes ผ่าน g.ax_heatmap เพิ่ม plt.Rectangle patch ที่ตำแหน่งเซลล์ที่ต้องการ พร้อมกำหนดสีขอบและความหนา

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

  1. ตั้งค่าขนาดรูปและเลย์เอาต์
  2. สร้าง DataFrame
  3. สร้าง clustermap ด้วย sns.clustermap()
  4. เข้าถึง heatmap axes: ax = g.ax_heatmap
  5. เพิ่ม Rectangle patch: ax.add_patch(plt.Rectangle((col, row), width, height, fill=False, edgecolor='yellow', lw=5))
  6. แสดงผล

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

import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame({"col1": [1, 4, 2, 3, 5], "col2": [3, 4, 1, 5, 2]})
g = sns.clustermap(df, figsize=(7.50, 3.50))
ax = g.ax_heatmap

border_color = "yellow"
ax.add_patch(plt.Rectangle((1, 2), 2, 1, fill=False, edgecolor=border_color, lw=5))
plt.show()

ผลลัพธ์

การเพิ่มขอบกำหนดเองให้เซลล์บางส่วนใน Matplotlib/Seaborn Heatmap