如何在 Matplotlib 中为条形图添加组标签?

matplotlibserver side programmingprogramming更新于 2025/4/30 19:52:17

要为条形图制作分组标签,我们可以采取以下步骤 −

  • 使用不同的数据元素为 labels、men_means 和 women_means 创建列表。

  • 使用 numpy.arrange() 方法返回给定间隔内均匀分布的值。

  • 设置宽度变量,即 width=0.35。

  • 使用 subplots  方法创建 fig  和 ax  变量,其中默认的 nrows 和 ncols 为1.

  • 条形图以给定的 *align*\ment 定位在 *x* 处。其尺寸由 *height* 和 *width* 指定。垂直基线为*底部*(默认为 0),因此使用 plt.bar() 方法创建 rect1  和 rect2 。

  • 使用 plt.ylabel() 方法设置 Y 轴标签。

  • 使用 set_title()  方法设置轴的标题。

  • 使用 set_xticks() 方法获取或设置 X 轴的当前刻度位置和标签。

  • 使用 set_xticklabels()  方法设置网格的 X 轴刻度标签。

  • 在图形上放置图例,使用 legend() 方法。

  • 使用autolabel()方法(即用户定义的方法)用一些标签注释创建的条形图(rect1 和 rect2)。

  • 要显示图形,请使用 plt.show() 方法。

示例

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
x = np.arange(len(labels))
width = 0.35
fig, ax = plt.subplots()
rects1 = ax.bar(x - width / 2, men_means, width, label='Men')
rects2 = ax.bar(x + width / 2, women_means, width, label='Women')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()

def autolabel(rects):
   for rect in rects:
      height = rect.get_height()
      ax.annotate('{}'.format(height),
         xy=(rect.get_x() + rect.get_width() / 2, height),
         xytext=(0, 3), # 3 points vertical offset
         textcoords="offset points",
         ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)
plt.show()

输出


相关文章