如何将 matplotlib 条形图中的数据标签旋转 90 度?

How to rotate data labels in matplotlib bar charts by 90 degrees?

我在条形图上使用类似这样的东西,每个条形图的外部都有数据标签(每个条形图的实际值):

import matplotlib.pyplot as plt
import numpy as np


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

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

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x, labels)
ax.legend()

ax.bar_label(rects1, padding=3)
ax.bar_label(rects2, padding=3)

fig.tight_layout()

plt.show()

结果如下所示:

如何将每个栏顶部的数据标签旋转 90 度? 我不是在问 xtick 标签。

bar_label uses Text 在引擎盖下并且可以接受它的参数,所以在这里我们可以传递 rotation=90rotation='vertical':

ax.bar_label(rects1, padding=3, rotation=90)
ax.bar_label(rects2, padding=3, rotation=90)