Để ghi phần trăm (hoặc giá trị) lên đỉnh mỗi cột bar chart, duyệt qua các patch cột và dùng ax.text().
Các bước
- Thiết lập figure size và autolayout.
- Tạo dữ liệu x, y và width.
- Tạo figure, axes và vẽ cột: pps = ax.bar(x, y, width).
- Duyệt pps, lấy height, ghi text ở vị trí đỉnh cột.
- Hiển thị bằng show().
Ví dụ
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = [1, 2, 3, 4, 5]
y = [3, 4, 2, 1, 3]
width = 0.35
fig, ax = plt.subplots()
pps = ax.bar(x, y, width, align='center')
for p in pps:
height = p.get_height()
ax.text(x=p.get_x() + p.get_width() / 2, y=height+.10, s="{}%".format(height), ha='center')
plt.show()
Kết quả
