matplotlib画柱状对比图
时间: 2023-05-25 13:03:26 浏览: 130
以下是使用matplotlib绘制柱状对比图的示例代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 示例数据
labels = ['Apple', 'Orange', 'Banana', 'Grape', 'Pineapple']
sales_2019 = [100, 90, 120, 80, 70]
sales_2020 = [120, 110, 100, 90, 80]
x = np.arange(len(labels))
width = 0.35 # 柱状体宽度
# 创建一张图表
fig, ax = plt.subplots()
# 绘制柱状对比图
rects1 = ax.bar(x - width/2, sales_2019, width, label='2019')
rects2 = ax.bar(x + width/2, sales_2020, width, label='2020')
# 设置图表标题及x轴、y轴标签
ax.set_title('Sales Comparison by Product', fontsize=16)
ax.set_xlabel('Product', fontsize=14)
ax.set_ylabel('Sales', fontsize=14)
# 设置x轴刻度标签
ax.set_xticks(x)
ax.set_xticklabels(labels)
# 设置图例
ax.legend()
# 在柱状顶部添加数值标签
def autolabel(rects):
for rect in rects:
height = rect.get_height()
ax.annotate('{:.0f}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3),
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
plt.show()
```
运行以上代码,将得到一张柱状对比图,如下所示:

在上述代码中,首先定义了示例数据,包括产品名称(labels)和2019年、2020年销售额(sales_2019, sales_2020)。然后,使用numpy模块产生x轴刻度值:`x = np.arange(len(labels))`。接着,定义柱状体的宽度:`width = 0.35`。
创建一张图表,包括一个坐标系ax:`fig, ax = plt.subplots()`。
使用`ax.bar()`方法绘制柱状对比图,分别表示2019年和2020年的销售额:`rects1 = ax.bar(x - width/2, sales_2019, width, label='2019')`,`rects2 = ax.bar(x + width/2, sales_2020, width, label='2020')`。
设置图表标题及x轴、y轴标签:`ax.set_title('Sales Comparison by Product', fontsize=16)`,`ax.set_xlabel('Product', fontsize=14)`,`ax.set_ylabel('Sales', fontsize=14)`。
设置x轴刻度标签:`ax.set_xticks(x)`,`ax.set_xticklabels(labels)`。
设置图例:`ax.legend()`。
在柱状体顶部添加数值标签,调用函数`autolabel()`实现:`autolabel(rects1)`,`autolabel(rects2)`。
最后,使用`plt.show()`方法显示图表。
阅读全文
相关推荐


















