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

การวาด Filled Arc (โค้งเติมสี) ใน Matplotlib

ใช้ ax.fill_between() เพื่อเติมสีพื้นที่ใต้โค้ง สร้างรูปทรงคล้าย Arc หรือ Sector ของวงกลม

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้าง Figure และ Subplots
  3. กำหนดรัศมี (r) และ Offset (yoff)
  4. สร้างข้อมูล X, Y สำหรับครึ่งวงกลม
  5. เติมสีระหว่างโค้งและแกน X ด้วย fill_between
  6. ตั้งค่า Aspect Ratio ให้เท่ากัน
  7. แสดงผล

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


import matplotlib.pyplot as plt
import numpy as np

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

fg, ax = plt.subplots(1, 1)

r = 2.0
yoff = -1.0

# สร้างข้อมูล x จาก -1 ถึง 1
x = np.arange(-1., 1.05, 0.05)
# สมการครึ่งวงกลม: y = sqrt(r - x^2) + yoff
y = np.sqrt(r - x ** 2) + yoff

# เติมสีระหว่างโค้ง y และ y=0
ax.fill_between(x, y, 0)

ax.axis([-2, 2, -2, 2])
ax.set_aspect("equal")
fg.canvas.draw()

plt.show()

การสร้าง Arc แบบเต็มวงกลม (Pie Slice)


import matplotlib.patches as patches

fig, ax = plt.subplots()
# สร้าง Wedge (sector)
wedge = patches.Wedge((0, 0), 1, 0, 90, 
                      facecolor='blue', alpha=0.5)
ax.add_patch(wedge)
ax.set_aspect('equal')
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
plt.show()

ผลลัพธ์

รูปทรงครึ่งวงกลมที่เติมสีอยู่เหนือแกน X จาก x=-1 ถึง x=1