Python怎么在柱形图上添加数字
时间: 2024-09-30 11:04:34 浏览: 34
在Python中,我们可以使用matplotlib库来创建柱状图,并在每个柱子上添加数字标签。下面是一个简单的例子:
```python
import matplotlib.pyplot as plt
import numpy as np
# 数据
bar_width = 0.35
x = np.arange(4)
menMeans = (20, 35, 30, 35) # 柱状图的数据
womenMeans = (25, 32, 34, 3.5)
# 创建图形
fig, ax = plt.subplots()
# 创建男性和女性的柱状图
rects1 = ax.bar(x - bar_width/2, menMeans, bar_width, label='Men')
rects2 = ax.bar(x + bar_width/2, womenMeans, bar_width, label='Women')
# 添加数值标签
for rect in rects1:
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') # 'bottom' for value below the bar
for rect in rects2:
height = rect.get_height()
ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(-3, 3), # negative vertical offset
textcoords="offset points",
ha='center', va='bottom')
# 其他配置
ax.set_xlabel('Groups')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4'))
ax.legend()
plt.show()
```
在这个示例中,我们使用了`annotate`函数来在每个柱子上放置数字,`xy`参数表示文字的位置,`xytext`参数则确定文本离柱子底部的距离。
阅读全文