python画双柱状图核心代码
时间: 2023-10-24 13:25:21 浏览: 38
可以使用Python的matplotlib库来绘制双柱状图,以下为核心代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 数据
men_means = [20, 35, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
labels = ['Group1', 'Group2', 'Group3', 'Group4', 'Group5']
x = np.arange(len(labels)) # x轴位置
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_xticks(x)
ax.set_xticklabels(labels)
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.legend()
plt.show()
```
其中,`men_means`和`women_means`分别存储了两组柱状图的数据,`labels`存储了每个柱状图对应的标签。使用`numpy`库的`arange()`函数生成了x轴上的位置,`width`为柱状图的宽度。在绘制柱状图时,使用`bar()`函数分别绘制了两组柱状图。最后通过`set_xticks()`和`set_xticklabels()`函数设置了x轴上的标签,并通过`set_ylabel()`和`set_title()`函数设置了纵轴标签和标题,使用`legend()`函数添加了图例。