Giới thiệu
Legend (chú thích) giúp người đọc hiểu nghĩa của các đường, cột, điểm trên biểu đồ. Matplotlib cung cấp plt.legend() với nhiều tùy chỉnh: vị trí, tiêu đề, đặt ngoài biểu đồ, annotation...
Dữ liệu mẫu
mobile = ['iPhone', 'Galaxy', 'Pixel']
units_sold = (
('2016', 12, 8, 6),
('2017', 14, 10, 7),
('2018', 16, 12, 8),
('2019', 18, 14, 10),
('2020', 20, 16, 5),
)
# Tách dữ liệu
years = [y for y, _, _, _ in units_sold]
iphone = [i for _, i, _, _ in units_sold]
galaxy = [g for _, _, g, _ in units_sold]
pixel = [p for _, _, _, p in units_sold]
pos = list(range(len(years)))
width = 0.2
Vẽ grouped bar chart với legend
import matplotlib.pyplot as plt
plt.bar([p - width for p in pos], iphone, width=width, color='green', label='iPhone')
plt.bar(pos, galaxy, width=width, color='blue', label='Galaxy')
plt.bar([p + width for p in pos], pixel, width=width, color='yellow', label='Pixel')
plt.xticks(pos, years)
plt.xlabel('Year')
plt.ylabel('Unit Sales (Millions)')
# Thêm legend
plt.legend(title='Manufacturers')
plt.show()
Thêm annotation (chú thích điểm dữ liệu)
# Pixel giảm 50% từ 2019 (10) xuống 2020 (5)
plt.annotate('50% Drop in Sales',
xy=(4.2, 5), # Vị trí mũi tên trỏ đến
xytext=(5.0, 12), # Vị trí text
horizontalalignment='center',
arrowprops=dict(facecolor='red', shrink=0.05))
Đặt legend bên ngoài biểu đồ
# bbox_to_anchor: (x, y) với (0,0) góc dưới trái, (1,1) góc trên phải
plt.legend(mobile, title='Manufacturers', bbox_to_anchor=(1.05, 0.8))
# Điều chỉnh margin để legend không bị cắt
plt.subplots_adjust(right=0.75)
plt.show()
Các tùy chỉnh legend phổ biến
| Tham số | Mô tả |
|---|---|
loc | Vị trí: 'best', 'upper right', 'lower left', 'center', ... |
bbox_to_anchor | Tọa độ tuyệt đối (axes fraction) để đặt legend tự do |
ncol | Số cột trong legend |
frameon | True/False: hiển thị khung viền |
shadow | True/False: đổ bóng |
fancybox | True/False: góc bo tròn |