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()
相关推荐
在屏幕前出油17 小时前
二、Python面向对象编程基础——理解self
开发语言·python
阿方索17 小时前
python文件与数据格式化
开发语言·python
信创天地19 小时前
信创国产化数据库的厂商有哪些?分别用在哪个领域?
数据库·python·网络安全·系统架构·系统安全·运维开发
不哦罗密经19 小时前
python相关
服务器·前端·python
happybasic19 小时前
python字典中字段重复性的分析~~
开发语言·python
山海青风19 小时前
人工智能基础与应用 - 数据处理、建模与预测流程 6 模型训练
人工智能·python·机器学习
l木本I20 小时前
Reinforcement Learning for VLA(强化学习+VLA)
c++·人工智能·python·机器学习·机器人
颖风船20 小时前
锂电池SOC估计的一种算法(改进无迹卡尔曼滤波)
python·算法·信号处理
94620164zwb520 小时前
应用设置模块 Cordova 与 OpenHarmony 混合开发实战
python
551只玄猫20 小时前
KNN算法基础 机器学习基础1 python人工智能
人工智能·python·算法·机器学习·机器学习算法·knn·knn算法