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

Chú thích subplot A, B, C trong figure Matplotlib

Để gán nhãn A, B, C... cho các subplot, duyệt axes flatten và dùng ax.text() với transform=ax.transAxes.

Các bước

  • Thiết lập figure size và autolayout.
  • Tạo subplot 1x3: fig, axs = plt.subplots(1, 3).
  • Làm phẳng axes: axs = axs.flat.
  • Duyệt enumerate(axs): vẽ ảnh ngẫu nhiên, ghi text string.ascii_uppercase[index] tại (0.45, 1.1) axes fraction.
  • Hiển thị bằng show().

Ví dụ

import numpy as np
from matplotlib import pyplot as plt
import string

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

fig, axs = plt.subplots(1, 3)
axs = axs.flat
for index, ax in enumerate(axs):
    ax.imshow(np.random.randn(4, 4), interpolation='nearest', cmap="copper")
    ax.text(0.45, 1.1, string.ascii_uppercase[index], transform=ax.transAxes, size=20, weight='bold')
plt.show()

Kết quả

Chú thích subplot A, B, C trong figure Matplotlib