如何使用 Matplotlib 繪製具有多個標籤的條形圖?


要在 Matplotlib 中繪製具有多個標籤的條形圖,可以採取以下步驟 -

  • 製作一些有關 men_means、men_std、women_meanswomen_std 的資料集。

  • 使用 numpy 製作索引資料點。

  • 初始化條形的 寬度

  • 使用 subplots() 方法建立圖形和一組子圖。

  • 使用 bar() 方法建立 rects1rects2 條形矩形。

  • 使用 set_ylabel()、set_title()、set_xticks()set_xticklabels() 方法。

  • 在圖形上放置一個圖例。

  • 使用 autolabel() 方法為條形圖新增多個標籤。

  • 要顯示圖形,請使用 show() 方法。

示例

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

輸出

更新於:2021 年 6 月 3 日

3 千次以上瀏覽

開啟你的職業生涯

完成課程以獲得認證

立即開始
廣告