下面是一个使用Matplotlib库来绘制带有标记的堆叠条形图的示例代码:
import numpy as np
import matplotlib.pyplot as plt
# 创建数据
categories = ['A', 'B', 'C', 'D', 'E'] # 类别
men_means = [20, 35, 30, 35, 27] # 男性数据
women_means = [25, 32, 34, 20, 25] # 女性数据
# 绘制堆叠条形图
fig, ax = plt.subplots()
width = 0.35 # 条形宽度
x = np.arange(len(categories)) # x轴坐标
ax.bar(x, men_means, width, label='Men')
ax.bar(x, women_means, width, bottom=men_means, label='Women')
# 添加数据标记
for i in range(len(categories)):
ax.text(x[i], men_means[i]/2, str(men_means[i]), ha='center', va='bottom')
ax.text(x[i], men_means[i] + women_means[i]/2, str(women_means[i]), ha='center', va='bottom')
# 设置图表标题和标签
ax.set_title('Stacked Bar Chart with Labels')
ax.set_xlabel('Categories')
ax.set_ylabel('Values')
ax.set_xticks(x)
ax.set_xticklabels(categories)
ax.legend()
# 显示图表
plt.show()
这段代码创建了一个包含5个类别的堆叠条形图,并在每个条形上方添加了数据标记。首先,我们定义了类别和对应的男性和女性数据。然后,使用ax.bar()
函数绘制了两个堆叠的条形图。接下来,使用ax.text()
函数在每个条形上方添加了数据标记。最后,设置了图表的标题、标签和图例,并通过plt.show()
函数显示图表。
下一篇:标记堆栈变量以进行垃圾回收