python绘制双柱图
时间: 2023-06-15 16:05:39 浏览: 143
要绘制双柱图,我们可以使用 Python 的 matplotlib 库。以下是一个简单的示例代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 数据
categories = ['A', 'B', 'C', 'D', 'E']
values1 = [20, 35, 30, 35, 27]
values2 = [25, 32, 34, 20, 25]
# 绘图
fig, ax = plt.subplots()
index = np.arange(len(categories))
bar_width = 0.35
opacity = 0.8
rects1 = ax.bar(index, values1, bar_width,
alpha=opacity,
color='b',
label='Value 1')
rects2 = ax.bar(index + bar_width, values2, bar_width,
alpha=opacity,
color='g',
label='Value 2')
ax.set_xlabel('Category')
ax.set_ylabel('Value')
ax.set_xticks(index + bar_width / 2)
ax.set_xticklabels(categories)
ax.legend()
plt.tight_layout()
plt.show()
```
代码中,我们首先定义了两个数据集 `values1` 和 `values2`,以及它们对应的类别 `categories`。接着,我们创建了一个画布和一个坐标系,使用 `bar` 方法绘制了两组柱形图。其中,`bar_width` 变量定义了每个柱形的宽度,`alpha` 变量定义了柱形的透明度,`color` 变量定义了柱形的颜色,`label` 变量定义了每组柱形的标签。
最后,我们设置了坐标轴标签和刻度,调用 `legend` 方法添加图例,并使用 `tight_layout` 方法调整布局。调用 `show` 方法显示图形。
执行上述代码,我们可以得到如下的双柱图:

阅读全文
相关推荐


















