Python 堆叠柱状图添加数据标签
1. 简介
在数据可视化领域,堆叠柱状图是一种常用的图表类型。它可以同时显示多个变量的数值,并以柱状图的方式展示它们之间的差异。在 Python 中,我们可以使用 Matplotlib 库来实现堆叠柱状图,并添加数据标签。
本文将向你介绍如何使用 Python 中的 Matplotlib 库来实现堆叠柱状图,并添加数据标签。我们将按照以下步骤进行操作:
- 准备数据
- 创建堆叠柱状图
- 添加数据标签
2. 准备数据
在实现堆叠柱状图之前,我们需要准备一些数据。假设我们有三个变量 A、B 和 C,每个变量在不同类别下的取值如下表所示:
类别 | A | B | C |
---|---|---|---|
类别1 | 10 | 20 | 30 |
类别2 | 15 | 25 | 35 |
类别3 | 5 | 15 | 25 |
我们可以将上述数据表示为 Python 中的二维列表或 Pandas 中的 DataFrame。
import pandas as pd
data = {
'A': [10, 15, 5],
'B': [20, 25, 15],
'C': [30, 35, 25]
}
df = pd.DataFrame(data)
3. 创建堆叠柱状图
接下来,我们使用 Matplotlib 库来创建堆叠柱状图。我们可以使用 bar
函数来绘制柱形图,然后使用 bottom
参数来指定每个柱形图的底部位置。
import matplotlib.pyplot as plt
categories = ['类别1', '类别2', '类别3']
colors = ['red', 'green', 'blue']
# 创建一个空的图表对象
fig, ax = plt.subplots()
# 遍历每个变量,绘制堆叠柱状图
bottom = [0] * len(categories) # 初始化底部位置
for var, color in zip(df.columns, colors):
ax.bar(categories, df[var], bottom=bottom, label=var, color=color)
bottom += df[var] # 更新底部位置
# 添加图例
ax.legend()
# 添加标题和坐标轴标签
ax.set_title('堆叠柱状图')
ax.set_xlabel('类别')
ax.set_ylabel('数值')
# 显示图表
plt.show()
上述代码中,我们首先创建了一个空的图表对象,然后使用 bar
函数绘制堆叠柱状图。通过遍历每个变量,并使用不同的颜色,我们可以绘制出堆叠柱状图。在绘制每个柱形图时,我们需要指定 bottom
参数为当前柱形图的底部位置。为了实现堆叠的效果,我们使用一个列表 bottom
来保存每个柱形图的底部位置,并在绘制每个柱形图后更新底部位置。
4. 添加数据标签
为了让堆叠柱状图更加直观,我们可以在每个柱形图上添加数据标签。可以使用 text
函数来实现这个功能。
# 创建一个空的图表对象
fig, ax = plt.subplots()
# 遍历每个变量,绘制堆叠柱状图
bottom = [0] * len(categories) # 初始化底部位置
for var, color in zip(df.columns, colors):
bars = ax.bar(categories, df[var], bottom=bottom, label=var, color=color)
bottom += df[var] # 更新底部位置
# 添加数据标签
for bar in bars:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width() / 2, height / 2, str(height), ha='center', va='center')
# 添加图例
ax.legend()
# 添加标题和坐标轴标签
ax.set_title('堆叠柱状图')
ax.set_xlabel('类别')
ax.set_ylabel('数