Để đặt viền Rectangle Matplotlib ra ngoài chiều rộng chỉ định, chúng ta có thể thực hiện các bước sau:
- Thiết lập kích thước figure và điều chỉnh padding giữa và xung quanh subplots.
- Tạo figure mới hoặc kích hoạt figure hiện có.
- Thêm ax vào figure như một phần của arrangement subplot.
- Khởi tạo biến line_width để đặt rectangle ra ngoài chiều rộng chỉ định. Dùng biến xy, w và h cho tâm, chiều rộng và chiều cao của rectangle.
- Lấy instance rectangle, với điểm neo xy và chiều cao, chiều rộng.
- Lấy instance offset transformbox.
- Thêm artist patch, r (Bước 5).
- Lấy container cho instance OffsetBox.
- Thêm annotation box, ab, vào container box.
- Để hiển thị figure, dùng phương thức show().
Ví dụ
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 / 2, xy[1] + h / 2), boxcoords="data", pad=0.52, fontsize=line_width,
bboxprops=dict(facecolor="none", edgecolor='r', lw=line_width))
ax.add_artist(ab)
plt.show()
Kết quả

