Python 利用pandas和matplotlib绘制堆叠柱状图

在数据可视化中,堆叠柱状图是一种常用的图表类型,它能够清晰地展示多个类别的数据,并突出显示每个类别中各部分的总量和组成比例。本文将演示如何使用 Python 的 pandas 和 matplotlib 库绘制优化的堆叠柱状图,并展示了销售数量随店铺名称变化的情况。

导入必要的库

首先,我们需要导入 pandas 和 matplotlib.pyplot 库,并指定中文字体为黑体,代码如下:

复制代码
import pandas as pd
import matplotlib.pyplot as plt

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

读取数据

接下来,我们使用 pandas 的 read_excel 函数读取 Excel 文件中的数据,并指定读取的工作表名称为"Sheet3",如下所示:

复制代码
df = pd.read_excel(r'C:\Users\liuchunlin2\Desktop\新建文件夹\新建 XLSX 工作表.xlsx', sheet_name='Sheet3')

设置图形参数

在绘制堆叠柱状图之前,我们需要设置柱状图的宽度和 x 轴的位置,代码如下:

复制代码
bar_width = 0.35  # 设置柱状图的宽度
x = df.index  # 设置x轴的位置

绘制堆叠柱状图

使用 matplotlib 库的 subplots 函数创建图形对象,并使用 bar 函数绘制堆叠柱状图,具体代码如下:

复制代码
fig, ax = plt.subplots()
rects1 = ax.bar(x, df['销售数量'], bar_width, label='销售数量')
rects2 = ax.bar(x, df['销售数量2'], bar_width, bottom=df['销售数量'], label='销售数量2')

添加标签和标题

我们为图形添加轴标签、标题、刻度和图例,使其更具可读性,具体代码如下:

复制代码
ax.set_xlabel('店铺名称')
ax.set_ylabel('销售数量')
ax.set_title('Stacked Bar Chart')
ax.set_xticks(x)
ax.set_xticklabels(df['店铺名称'])
ax.legend()

显示数据标签

最后,我们使用 annotate 函数在每个柱子上方显示数据标签,以展示具体的销售数量,具体代码如下:

复制代码
for rect in rects1:
    height = rect.get_height()
    ax.annotate(f'{height}', xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3),
                textcoords='offset points', ha='center', va='bottom')

for rect1, rect2 in zip(rects1, rects2):
    height1 = rect1.get_height()
    height2 = rect2.get_height()
    total_height = height1 + height2
    ax.annotate(f'{height2}', xy=(rect2.get_x() + rect2.get_width() / 2, total_height), xytext=(0, 3),
                textcoords='offset points', ha='center', va='bottom')

显示图形

最后,使用 plt.show() 函数显示绘制好的堆叠柱状图,代码如下:

复制代码
plt.show()

通过以上步骤,我们成功绘制出了堆叠柱状图,展示了不同店铺的销售数量情况。

图表效果图展示

完整代码:

复制代码
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = ['SimHei']  # 指定中文字体为黑体
# 读取Excel文件
df = pd.read_excel(r'C:\Users\liuchunlin2\Desktop\新建文件夹\新建 XLSX 工作表.xlsx', sheet_name='Sheet3')
# 设置柱状图的宽度
bar_width = 0.35
# 设置x轴的位置
x = df.index

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

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

# 在每个柱子上方显示数据标签
for rect in rects1:
    height = rect.get_height()
    ax.annotate(f'{height}', xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3),
                textcoords='offset points', ha='center', va='bottom')

for rect1, rect2 in zip(rects1, rects2):
    height1 = rect1.get_height()
    height2 = rect2.get_height()
    total_height = height1 + height2
    ax.annotate(f'{height2}', xy=(rect2.get_x() + rect2.get_width() / 2, total_height), xytext=(0, 3),
                textcoords='offset points', ha='center', va='bottom')

# 显示图形
plt.show()
相关推荐
AI逐月1 小时前
解决 ComfyUI 插件安装后 Nanobind 报错问题:soxr 版本冲突原理解读
开发语言·python
AC赳赳老秦1 小时前
Windows 系统 OpenClaw 执行策略报错及管理员权限设置深度解析与实操指南
运维·人工智能·python·django·自动化·媒体·openclaw
软件开发技术深度爱好者1 小时前
用python + pillow实现GUI界面图片GUI处理工具
开发语言·python
FreakStudio1 小时前
ESP32 实现在线动态安装库和自动依赖安装-使用uPyPI包管理平台
python·单片机·嵌入式·面向对象·电子diy·sourcetrail
别抢我的锅包肉2 小时前
【FastAPI】 响应类型详解:从默认 JSON 到自定义响应
python·fastapi
智算菩萨2 小时前
【Tkinter】15 样式与主题深度解析:ttk 主题系统、Style 对象与跨平台样式管理实战
开发语言·python·ui·ai编程·tkinter
weixin_419349792 小时前
Python 项目中生成 requirements.txt 文件
开发语言·python
第一程序员2 小时前
Python与区块链:非科班转码者的指南
python·github
liu****3 小时前
LangChain-AI应用开发框架(六)
人工智能·python·langchain·大模型应用·本地部署大模型
witAI3 小时前
**AI仿真人剧制作2025推荐,专业团队与创新技术引领未来**
人工智能·python