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

Hướng dẫn thêm chú thích (legend) cho biểu đồ Matplotlib Python

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

Code hoàn chỉnh

import matplotlib.pyplot as plt

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))

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

plt.bar([p - width for p in pos], iphone, width=width, color='green')
plt.bar(pos, galaxy, width=width, color='blue')
plt.bar([p + width for p in pos], pixel, width=width, color='yellow')

plt.xticks(pos, years)
plt.xlabel('Yearly Sales')
plt.ylabel('Unit Sales In Millions')

# Annotation
plt.annotate('50% Drop in Sales', xy=(4.2, 5), xytext=(5.0, 12),
             ha='center', arrowprops=dict(facecolor='red', shrink=0.05))

# Legend ngoài biểu đồ
plt.legend(mobile, title='Manufacturers', bbox_to_anchor=(1.05, 0.8))
plt.subplots_adjust(right=0.75)

# Lưu file
plt.savefig('MobileSales.png', bbox_inches='tight')
plt.show()

Kết quả

Biểu đồ cột nhóm 3 hãng, có legend bên phải, annotation đỏ chỉ ra sự sụt giảm của Pixel năm 2020.

Tham sốMô tả
locVị trí: 'best', 'upper right', 'lower left', 'center', ...
bbox_to_anchorTọa độ tuyệt đối (axes fraction) để đặt legend tự do
ncolSố cột trong legend
frameonTrue/False: hiển thị khung viền
shadowTrue/False: đổ bóng
fancyboxTrue/False: góc bo tròn