如何在Matplotlib中绘制具有多个标签的条形图?
要在Matplotlib中绘制具有多个标签的条形图,可以按照以下步骤进行操作−
- 创建 men_means, men_std, women_means, 和 women_std 的数据集。
-
使用numpy创建索引数据点。
-
初始化 bars 的宽度。
-
使用 subplots() 方法创建一个图和一组子图。
-
使用 bar() 方法创建 rects1 和 rects2 条形矩形。
-
使用 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)) # 组的x位置
width = 0.35 # 条形的宽度
fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std, label='男性')
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std, label='女性')
ax.set_ylabel('成绩')
ax.set_title('组分和性别的成绩')
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), # 使用3个点的偏移量
textcoords="offset points", # 在两个方向上
ha=ha[xpos], va='bottom')
autolabel(rects1, "left")
autolabel(rects2, "right")
plt.show()
输出
