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

วิธาดึงพิกัด (Coordinates) จาก Contour Plot ใน Matplotlib

ภาพรวม

Contour plot แสดงเส้นระดับ (contour lines) ของข้อมูล 3 มิติบนระนาบ 2 มิติ บทความนี้สาธิตวิธาดึงพิกัดจุดบนเส้น contour กลับมาใช้งาน

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

  • กำหนดขนาดฟิกเกอร์และปรับ padding
  • สร้างข้อมูล x, y และเมทริกซ์ m
  • สร้าง contour plot ด้วย plt.contour(x, y, m)
  • เข้าถึง cs.collections เพื่อดึง path ของแต่ละเส้น contour
  • ใช้ get_paths() และ .vertices เพื่อดึงพิกัด
  • แสดงผลและพิมพ์พิกัดบน terminal

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

import matplotlib.pyplot as plt

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

x = [1, 2, 3, 4]
y = [1, 2, 3, 4]
m = [[15, 14, 13, 12],
     [14, 12, 10, 8],
     [13, 10, 7, 4],
     [12, 8, 4, 0]]

cs = plt.contour(x, y, m)

for collection in cs.collections:
    for path in collection.get_paths():
        vertices = path.vertices
        print(vertices[:, 0], vertices[:, 1])

plt.show()

ผลลัพธ์

Contour plot พร้อมพิกัดที่พิมพ์ออกมาบน console

วิธาดึงพิกัด (Coordinates) จาก Contour Plot ใน Matplotlib วิธาดึงพิกัด (Coordinates) จาก Contour Plot ใน Matplotlib

[4.] [4.]
[4. 3.5] [3.5 4.]
[4. 3.] [3. 4.]
[4. 3.333 3. 2.5] [2.5 3. 3.333 4.]
...

ประยุกต์ใช้

  • นำพิกัดไปสร้าง polygon หรือ shape อื่นๆ
  • คำนวณพื้นที่ภายใน contour
  • Export ไป GIS หรือ CAD software