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

Vẽ biểu đồ cột nhiều nhóm có nhãn giá trị trong Matplotlib

Để vẽ grouped bar chart với nhãn giá trị trên mỗi cột, ta dùng ax.bar() hai lần (cho 2 nhóm) và hàm autolabel() để ghi số liệu.

Các bước

  • Chuẩn bị dữ liệu means/std cho 2 nhóm (Men/Women).
  • Tạo index và width cho cột.
  • Tạo figure, axes.
  • Vẽ 2 nhóm cột lệch nhau ind - width/2 và ind + width/2.
  • Thiết lậpylabel, title, xticks, xticklabels, legend.
  • Định nghĩa hàm autolabel(rects, xpos) ghi text trên cột.
  • Gọi autolabel cho 2 nhóm.
  • 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

men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)
ind = np.arange(len(men_means))
width = 0.35
fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std, label='Men')
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std, label='Women')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend()
def autolabel(rects, xpos='center'):
    ha = {'center': 'center', 'right': 'left', 'left': 'right'}
    offset = {'center': 0, 'right': 1, 'left': -1}
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(offset[xpos]*3, 3), textcoords="offset points", ha=ha[xpos], va='bottom')
autolabel(rects1, "left")
autolabel(rects2, "right")
plt.show()

Kết quả

Vẽ biểu đồ cột nhiều nhóm có nhãn giá trị trong Matplotlib