Python 利用pandas和matplotlib绘制双柱状图

发布时间 2023-11-06 21:49:02作者: qwerrt9

在数据分析和可视化中,常用的一种图形类型是柱状图。柱状图能够清晰地展示不同分类变量的数值,并支持多组数据进行对比。本篇文章将介绍如何使用Python绘制双柱状图。

准备工作

在开始绘制柱状图之前,需要先安装matplotlib和pandas这两个Python库。可以通过pip安装:

pip install matplotlib 
pip install pandas

导入所需库

import pandas as pd
import matplotlib.pyplot as plt

读取并处理数据

# 读取Excel文件
df = pd.read_excel(r'C:\Users\Admin\Desktop\数据核对\新建 XLSX 工作表.xlsx', sheet_name='Sheet3')

# 设置柱状图的宽度
bar_width = 0.35

# 设置x轴的位置
x = df.index

首先使用Pandas读取Excel文件,然后根据实际情况设置柱状图的宽度和x轴位置。这里我们使用DataFrame的索引作为x轴。

绘制柱状图

# 绘制柱状图
fig, ax = plt.subplots()
rects1 = ax.bar(x - bar_width/2, df['销售数量'], bar_width, label='销售数量')
rects2 = ax.bar(x + bar_width/2, df['销售数量2'], bar_width, label='销售数量2')

使用matplotlib绘制柱状图,其中subplots()方法会返回一个Figure对象和一个Axes对象。然后使用bar()方法绘制两组柱状图,并设置标签。

添加标签和标题

# 添加标签和标题
ax.set_xlabel('店铺名称')
ax.set_ylabel('销售数量')
ax.set_title('Double Bar Chart')
ax.set_xticks(x)
ax.set_xticklabels(df['店铺名称'])
ax.legend()

添加数据标签

# 添加数据标签
for rect in rects1:
    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')

for rect in rects2:
    height = rect.get_height()
    ax.annotate('{}'.format(height),
                xy=(rect.get_x() + rect.get_width() / 2, height/2),
                xytext=(0, 3),  # 3 points vertical offset
                textcoords="offset points",
                ha='center', va='top')

对于每个柱状图,使用annotate()方法添加数据标签。

显示图形

# 显示图形
plt.show()

最后使用show()方法显示图形。

完整代码


import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = ['SimHei']  # 指定中文字体为黑体

# 读取Excel文件
df = pd.read_excel(r'C:\Users\Admin\Desktop\数据核对\新建 XLSX 工作表.xlsx', sheet_name='Sheet3')

# 设置柱状图的宽度
bar_width = 0.35

# 设置x轴的位置
x = df.index

# 绘制柱状图
fig, ax = plt.subplots()
rects1 = ax.bar(x - bar_width/2, df['销售数量'], bar_width, label='销售数量')
rects2 = ax.bar(x + bar_width/2, df['销售数量2'], bar_width, label='销售数量2')

# 添加标签和标题
ax.set_xlabel('店铺名称')
ax.set_ylabel('销售数量')
ax.set_title('Double Bar Chart')
ax.set_xticks(x)
ax.set_xticklabels(df['店铺名称'])
ax.legend()

# 添加数据标签
for rect in rects1:
    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')

for rect in rects2:
    height = rect.get_height()
    ax.annotate('{}'.format(height),
                xy=(rect.get_x() + rect.get_width() / 2, height/2),
                xytext=(0, 3),  # 3 points vertical offset
                textcoords="offset points",
                ha='center', va='top')

# 显示图形
plt.show()