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

วิธีดึงพิกัดพิกเซล (Pixel Coordinates) จาก Scatter Plot ของ Matplotlib

ภาพรวม

บางครั้งต้องการพิกัดพิกเซลจริงบน canvas สำหรับการคลิก mouse, tooltip หรือ export ข้อมูล ใช้ transformation pipeline ของ matplotlib

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

  • กำหนดขนาดฟิกเกอร์
  • สร้าง scatter plot แบบสุ่ม
  • ดึงข้อมูล x, y ด้วย get_data()
  • แปลงจาก data coordinates เป็น pixel coordinates ด้วย ax.transData.transform()
  • ปรับแกน Y ให้ตรงกับระบบพิกัดหน้าจอ (origin อยู่มุมบนซ้าย)
  • ดึงขนาด canvas ด้วย fig.canvas.get_width_height()
  • พิมพ์พิกัดพิกเซลออกมา

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

import numpy as np
import matplotlib.pyplot as plt

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

n = 10
fig, ax = plt.subplots()
points, = ax.plot(np.random.random(n), np.random.random(n), 'r*')

x, y = points.get_data()
pixels = ax.transData.transform(np.vstack([x, y]).T)
x_px, y_px = pixels.T

width, height = fig.canvas.get_width_height()
y_px = height - y_px  # flip Y axis

print("The pixel coordinates are:")
for xp, yp in zip(x_px, y_px):
    print(f'{xp:0.2f}\t{yp:0.2f}')

plt.show()

ผลลัพธ์

Scatter plot พร้อมพิมพ์พิกัดพิกเซลบน console

วิธีดึงพิกัดพิกเซล (Pixel Coordinates) จาก Scatter Plot ของ Matplotlib วิธีดึงพิกัดพิกเซล (Pixel Coordinates) จาก Scatter Plot ของ Matplotlib

The pixel coordinates are:
564.93  161.83
446.27  112.60
153.39  247.65
...

คำอธิบาย Transform

  • ax.transData – transform จาก data coordinates ไป display coordinates
  • ax.transAxes – transform จาก axes coordinates (0-1) ไป display
  • fig.transFigure – transform จาก figure coordinates ไป display
  • ต้อง flip Y เพราะ matplotlib origin อยู่ล่างซ้าย แต่ pixel origin อยู่บนซ้าย