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

การวาดวงกลมภายในสี่เหลี่ยมผืนผ้าใน Matplotlib


วางวงกลมอยู่ในสี่เหลี่ยมผืนผ้า

สร้าง rectangle และ circle patch แล้วเพิ่มลง axes เดียวกัน

ขั้นตอน

  1. สร้าง figure ด้วย figure()
  2. เพิ่ม subplot
  3. สร้าง rectangle และ circle instance
  4. เพิ่ม rectangle patch ลง axes
  5. เพิ่ม circle patch ลง axes
  6. ปรับขนาดแกน x, y ด้วย xlim() และ ylim()
  7. แสดงด้วย show()

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

import matplotlib
from matplotlib import pyplot as plt, patches

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

fig = plt.figure()
ax = fig.add_subplot(111)

rect = patches.Rectangle((2, 2), 8, 5, color='yellow')
circle = patches.Circle((6, 4.5), radius=2, color='red')

ax.add_patch(rect)
ax.add_patch(circle)

plt.xlim([-10, 10])
plt.ylim([-10, 10])
plt.axis('equal')
plt.show()

ผลลัพธ์

การวาดวงกลมภายในสี่เหลี่ยมผืนผ้าใน Matplotlib