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

Thêm chú giải cho boxplot đa nhóm trên cùng axes Matplotlib

Để thêm legend cho nhiều boxplot vẽ chồng lên cùng một axes, ta lấy artist "boxes" từ kết quả boxplot để làm handle cho legend.

Các bước

  • Thiết lập figure size và autolayout.
  • Tạo 2 tập dữ liệu ngẫu nhiên a, b (100x2).
  • Tạo figure và axes.
  • Vẽ 2 boxplot ở vị trí khác nhau (positions), bật patch_artist=True để tô màu.
  • Tạo legend từ bp1["boxes"][0] và bp2["boxes"][0].
  • Hiển thị bằng show().

Ví dụ

import matplotlib.pyplot as plt
import numpy as np

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

a = np.random.rand(100, 2)
b = np.random.rand(100, 2)
fig = plt.figure()
ax = fig.add_subplot(111)
bp1 = ax.boxplot(a, positions=[1, 3], notch=True, widths=0.35, patch_artist=True, boxprops=dict(facecolor="C0"))
bp2 = ax.boxplot(b, positions=[0, 2], notch=True, widths=0.35, patch_artist=True, boxprops=dict(facecolor="C2"))
ax.legend([bp1["boxes"][0], bp2["boxes"][0]], ["Box Plot 1", "Box Plot 2"], loc='upper right')
plt.show()

Kết quả

Thêm chú giải cho boxplot đa nhóm trên cùng axes Matplotlib