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()
相关推荐
小白—人工智能12 分钟前
数据分析 —— 数据预处理
python·数据挖掘·数据分析
若叶时代15 分钟前
数据分析_Python
人工智能·python·数据分析
英英_24 分钟前
python 爬虫框架介绍
开发语言·爬虫·python
大模型铲屎官1 小时前
【Python-Day 14】玩转Python字典(上篇):从零开始学习创建、访问与操作
开发语言·人工智能·pytorch·python·深度学习·大模型·字典
yunvwugua__2 小时前
Python训练营打卡 Day27
开发语言·python
Stara05112 小时前
基于多头自注意力机制(MHSA)增强的YOLOv11主干网络—面向高精度目标检测的结构创新与性能优化
人工智能·python·深度学习·神经网络·目标检测·计算机视觉·yolov11
那雨倾城4 小时前
使用 OpenCV 将图像中标记特定颜色区域
人工智能·python·opencv·计算机视觉·视觉检测
LuckyTHP6 小时前
java 使用zxing生成条形码(可自定义文字位置、边框样式)
java·开发语言·python
mahuifa8 小时前
(7)python开发经验
python·qt·pyside6·开发经验
学地理的小胖砸9 小时前
【Python 操作 MySQL 数据库】
数据库·python·mysql