以下是使用matplotlib库绘制百分比子组柱状图的示例代码:
import matplotlib.pyplot as plt
import numpy as np
# 数据
labels = ['A', 'B', 'C', 'D']
group1 = [20, 35, 30, 10]
group2 = [15, 30, 25, 20]
# 计算每组的百分比
total1 = sum(group1)
total2 = sum(group2)
percent1 = [x / total1 * 100 for x in group1]
percent2 = [x / total2 * 100 for x in group2]
# 绘图
width = 0.35
x = np.arange(len(labels))
fig, ax = plt.subplots()
ax1 = ax.bar(x - width/2, percent1, width, label='Group 1')
ax2 = ax.bar(x + width/2, percent2, width, label='Group 2')
# 添加标签
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.set_ylabel('Percentage')
# 添加图例
ax.legend()
# 添加百分比标签
def autolabel(rects):
for rect in rects:
height = rect.get_height()
ax.annotate(f'{height:.1f}%', xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), textcoords="offset points",
ha='center', va='bottom')
autolabel(ax1)
autolabel(ax2)
plt.show()
运行以上代码,将显示一个包含两个子组的百分比柱状图,其中每个柱子表示一组数据,并显示该组数据在总数中所占的百分比。
下一篇:百分比总和熊猫矩阵