Computer >> Máy Tính >  >> Lập trình >> Python

Làm thế nào để vẽ một Biểu đồ thanh với nhiều nhãn trong Matplotlib?

Để vẽ biểu đồ thanh có nhiều nhãn trong Matplotlib, chúng ta có thể thực hiện các bước sau -

  • Tạo một số tập dữ liệu cho men_means, men_std, women_means, women_std .

  • Tạo các điểm dữ liệu chỉ mục bằng cách sử dụng numpy.

  • Khởi tạo chiều rộng của các thanh.

  • Sử dụng ô con () phương pháp tạo hình và tập hợp các ô con.

  • Tạo rects1 rects2 thanh hình chữ nhật bằng cách sử dụng bar () phương pháp.

  • Sử dụng set_ylabel (), set_title () , set_xticks () set_xticklabels () phương pháp.

  • Đặt một huyền thoại vào cốt truyện.

  • Thêm nhiều nhãn cho biểu đồ thanh bằng cách sử dụng autolabel () phương pháp.

  • Để hiển thị hình này, hãy sử dụng show () phương pháp.

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)) # the x locations for the groups
width = 0.35 # the width of the bars

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), # use 3 points offset
         textcoords="offset points", # in both directions
         ha=ha[xpos], va='bottom')

autolabel(rects1, "left")
autolabel(rects2, "right")
plt.show()

Đầu ra

Làm thế nào để vẽ một Biểu đồ thanh với nhiều nhãn trong Matplotlib?