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

在数据分析和可视化中,常用的一种图形类型是柱状图。柱状图能够清晰地展示不同分类变量的数值,并支持多组数据进行对比。本篇文章将介绍如何使用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()
相关推荐
Bert.Cai5 分钟前
Python字面量详解
开发语言·python
Flying pigs~~8 分钟前
基于Deepseek大模型API完成文本分类预测功能
java·前端·人工智能·python·langchain·deepseek
Ujimatsu33 分钟前
数据分析相关面试题-Python部分
大数据·python·数据分析
未知鱼34 分钟前
Python安全开发之简易Xss检测工具(详细注释)
python·安全·xss
yaoxin52112342 分钟前
368. Java IO API - 基本文件属性
java·开发语言·python
程序媛徐师姐1 小时前
Python基于机器学习的就业岗位推荐系统【附源码、文档说明】
python·机器学习·python机器学习·就业岗位推荐系统·python就业岗位推荐系统·python机器学习就业推荐·就业岗位推荐
建军啊1 小时前
java审计进阶
java·开发语言·python
码界筑梦坊1 小时前
329-基于Python的交通流量数据可视化分析系统
开发语言·python·信息可视化·数据分析·django·vue·毕业设计
zzb15801 小时前
Agent记忆与检索
java·人工智能·python·学习·ai