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

Python Matplotlib - ตั้ง xticks และ yticks สำหรับ imshow Plot

ใช้ ax.set_xticks() และ ax.set_yticks() กำหนดตำแหน่ง Ticks บน Heatmap/Image จาก imshow()

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

import numpy as np
import matplotlib.pyplot as plt

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

ax = plt.gca()
data = np.random.rand(6, 6)

ax.imshow(data)

# Set ticks at positions 1,2,3,4,5
ax.set_xticks([1, 2, 3, 4, 5])
ax.set_yticks([1, 2, 3, 4, 5])

plt.show()

คำอธิบาย

  • imshow(data) แสดง 2D Array เป็น Image (Heatmap)
  • Default: Ticks อยู่ที่ Index 0,1,2,3,4,5 (6 จุด)
  • set_xticks([1,2,3,4,5]) แสดง Ticks ที่ตำแหน่ง 1-5 เท่านั้น
  • เพิ่ม Labels: ax.set_xticklabels(['A','B','C','D','E'])
  • สำหรับ Center Ticks ระหว่าง Cell: ใช้ np.arange(0.5, 6.5)