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

วิธีตั้งค่าขอบ Rectangle ให้อยู่นอกความกว้างที่ระบุใน Matplotlib

ในการตั้งค่าขอบ Rectangle ให้อยู่นอกความกว้างที่ระบุใน Matplotlib เราสามารถทำตามขั้นตอนต่อไปนี้:

  • ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
  • สร้าง figure ใหม่หรือเปิดใช้งาน figure ที่มีอยู่
  • เพิ่ม ax ให้กับ figure เป็นส่วนหนึ่งของ subplot arrangement
  • เริ่มต้นตัวแปร line_width เพื่อตั้งค่ารูปสี่เหลี่ยมอยู่นอกความกว้างที่ระบุ ใช้ตัวแปร xy, w และ h สำหรับจุดกึ่งกลาง ความกว้าง และความสูงของรูปสี่เหลี่ยม
  • รับอินสแตนซ์สี่เหลี่ยม พร้อมจุดลอย xy และความสูงความกว้าง
  • รับอินสแตนซ์ offset transformbox
  • เพิ่ม artist patch, r (ขั้นตอน 5)
  • รับคอนเทนเนอร์สำหรับอินสแตนซ์ OffsetBox
  • เพิ่มกล่อง annotation, ab, ให้กับกล่องคอนเทนเนอร์
  • เพื่อแสดงรูป ใช้เมธอด show()

ตัวอย่าง

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.offsetbox import AnnotationBbox, AuxTransformBox

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

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 6, 8, 6])

line_width = 7
xy, w, h = (1, 3), 2, 2
r = Rectangle(xy, w, h, fc='green', ec='orange', lw=3)

offsetbox = AuxTransformBox(ax.transData)
offsetbox.add_artist(r)

ab = AnnotationBbox(offsetbox, (xy[0] + w /, xy[1] + w /), boxcoords="data", pad=0.52, fontsize=line_width,
    bboxprops=dict(facecolor="none", edgecolor='r', lw=line_width))

ax.add_artist(ab)
plt.show()

ผลลัพธ์

วิธีตั้งค่าขอบ Rectangle ให้อยู่นอกความกว้างที่ระบุใน Matplotlibวิธีตั้งค่าขอบ Rectangle ให้อยู่นอกความกว้างที่ระบุใน Matplotlib