如何在Jupyter中基于多变量制作100%占比的分类堆叠条形图
在Jupyter中创建100%比例分类堆叠条形图
1. 导入所需库
import pandas as pd import matplotlib.pyplot as plt
2. 准备/导入数据
将下方模拟数据替换为你的实际数据(也可通过pd.read_excel("你的文件路径.xlsx")或pd.read_csv("你的文件路径.csv")直接读取表格):
# 示例数据结构,对应你的表格格式 data = { "类别": ["类别1", "类别2", "类别3", "类别4"], "Cluster_1": [12, 18, 9, 22], "Cluster_2": [28, 24, 32, 19], "Cluster_3": [60, 58, 59, 59] } df = pd.DataFrame(data)
3. 将数据转换为100%占比格式
# 按行计算总和,再将每个Cluster的数值转换为该行的百分比 df_percent = df.set_index("类别").div(df.set_index("类别").sum(axis=1), axis=0) * 100
4. 绘制堆叠条形图
# 设置基础绘图风格 plt.style.use('seaborn-v0_8') # 创建堆叠条形图 ax = df_percent.plot(kind='bar', stacked=True, figsize=(10, 6)) # 配置图表文本 plt.title('100% 分类堆叠条形图', fontsize=14) plt.xlabel('类别', fontsize=12) plt.ylabel('百分比 (%)', fontsize=12) # 给每个堆叠块添加百分比标签 for p in ax.patches: width, height = p.get_width(), p.get_height() x, y = p.get_xy() if height > 0.5: # 过滤极小占比的标签,避免重叠 ax.text(x + width/2, y + height/2, f'{height:.1f}%', ha='center', va='center', fontsize=10) # 调整图例位置,避免遮挡图表 plt.legend(title='聚类分组', bbox_to_anchor=(1.05, 1), loc='upper left') # 自动调整布局 plt.tight_layout() # 显示图表 plt.show()
关键提示
- 若你的表格第一列不是类别列,需调整
set_index中的列名,确保按类别分组计算占比。 - 可通过修改
figsize参数调整图表尺寸,修改fontsize调整文本大小,适配你的展示需求。
内容的提问来源于stack exchange,提问作者Farshid Owrang
相关产品推荐
相关产品推荐

