matplotlib并列柱形图编写代码
时间: 2023-07-03 09:32:03 浏览: 90
以下是使用Matplotlib绘制并列柱形图的代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
labels = ['A', 'B', 'C', 'D', 'E'] # 横坐标标签
men_means = [20, 35, 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_xlabel('Group')
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()
```
运行上述代码将生成一个并列柱形图,其中包含两组数据,每组数据包含五个柱子。
注:本例中的数据是随机生成的。您可以根据实际需求更改数据。
阅读全文