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

วิธีพล็อตวงกลมครึ่งดำครึ่งขาวด้วย Matplotlib

การสร้างวงกลมแบ่งสีครึ่งดำครึ่งขาว

ใช้ Wedge patch สองชิ้นครอบคลุม 180 องศาแต่ละชิ้น

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • สร้าง figure และ subplots
  • กำหนด theta1=0, theta2=180 สำหรับครึ่งแรก
  • สร้าง Wedge สองอัน: สีดำ (0-180) และ สีขาว (180-360)
  • เพิ่ม artist ทั้งสองด้วย ax.add_artist()
  • ตั้งค่า axis('equal') และ xlim, ylim
  • แสดงผลด้วย show()

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

import matplotlib.pyplot as plt
from matplotlib.patches import Wedge

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

fig, ax = plt.subplots()
theta1, theta2 = 0, 0 + 180
radius = 2
center = (0, 0)

w1 = Wedge(center, radius, theta1, theta2, fc='black', edgecolor='black')
w2 = Wedge(center, radius, theta2, theta1, fc='white', edgecolor='black')

for wedge in [w1, w2]:
    ax.add_artist(wedge)

ax.axis('equal')
ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)
plt.show()

คำอธิบาย

Wedge สร้างรูปแท่งโค้ง (pie slice) fc=face color edgecolor=ขอบ