Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Vẽ hình chữ nhật có màu viền (edgecolor) trong Matplotlib

Tương tự vẽ hình tròn, dùng matplotlib.patches.Rectangle.

  • Tạo figure, thêm subplot.
  • Tạo Rectangle với góc (-1,-1), width=3, height=3, edgecolor='orange', facecolor='green', linewidth=5.
  • add_patch(rect).
  • Đặt text ở giữa.
  • xlim, ylim, show().

Ví dụ

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 = matplotlib.patches.Rectangle((-1, -1), 3, 3, edgecolor='orange', facecolor="green", linewidth=5)
ax.add_patch(rect)
plt.text(0, 0.5, "Rectangle")
plt.xlim([-4, 4])
plt.ylim([-4, 4])
plt.show()

Kết quả

Hình chữ nhật màu xanh lá với viền cam dày, chữ "Rectangle" ở giữa.