1设计并实现带标签的分组条形图 此示例显示如何创建分组条形图以及如何使用标签注释条形图。 import matplotlib.pyplot as plt import numpy as np
时间: 2023-12-09 16:06:36 浏览: 75
以下是一个带标签的分组条形图的示例代码,您可以根据自己的需要进行调整:
```python
import matplotlib.pyplot as plt
import numpy as np
# 数据
labels = ['A', 'B', 'C', 'D']
men_means = [20, 35, 30, 35]
women_means = [25, 32, 34, 20]
width = 0.35 # 条形图宽度
# 创建图形
fig, ax = plt.subplots()
rects1 = ax.bar(np.arange(len(labels))-width/2, men_means, width, label='Men')
rects2 = ax.bar(np.arange(len(labels))+width/2, women_means, width, label='Women')
# 添加标签和值
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)
# 设置图形属性
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(np.arange(len(labels)))
ax.set_xticklabels(labels)
ax.legend()
plt.show()
```
运行代码后,可以得到以下的图形:
![带标签的分组条形图示例](https://i.imgur.com/3jUvM9w.png)
阅读全文