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()
相关推荐
wxin_VXbishe22 分钟前
springboot合肥师范学院实习实训管理系统-计算机毕业设计源码31290
java·spring boot·python·spring·servlet·django·php
ITenderL28 分钟前
Python学习笔记-函数
python·学习笔记
zmjia11130 分钟前
全流程Python编程、机器学习与深度学习实践技术应用
python·深度学习·机器学习
_.Switch1 小时前
Python机器学习:自然语言处理、计算机视觉与强化学习
python·机器学习·计算机视觉·自然语言处理·架构·tensorflow·scikit-learn
JUNAI_Strive_ving1 小时前
番茄小说逆向爬取
javascript·python
彤银浦1 小时前
python学习记录7
python·学习
简单.is.good2 小时前
【测试】接口测试与接口自动化
开发语言·python
Envyᥫᩣ2 小时前
Python中的自然语言处理:从基础到高级
python·自然语言处理·easyui
哪 吒2 小时前
华为OD机试 - 几何平均值最大子数(Python/JS/C/C++ 2024 E卷 200分)
javascript·python·华为od
我是陈泽2 小时前
一行 Python 代码能实现什么丧心病狂的功能?圣诞树源代码
开发语言·python·程序员·编程·python教程·python学习·python教学