You need to enable JavaScript to run this app. Python中基于Pandas DataFrame按Cluster分组绘制水平堆叠柱状图的方法
优惠活动
大模型
产品
解决方案
定价
更多

Python中基于Pandas DataFrame按Cluster分组绘制水平堆叠柱状图的方法

按Cluster分组绘制水平堆叠投资构成柱状图

前置准备与数据聚合

实现该图表的核心逻辑是:先按照Cluster维度对所有投资类指标做分组聚合,得到每个聚类组下各类投资的累计规模,再基于聚合结果绘制堆叠条形。
具体步骤如下:

  • 导入依赖库
import pandas as pd
import matplotlib.pyplot as plt
  • 构造对应你提供的结构的示例DataFrame
data = {
    'BondInvestments': [10, 10, 200, 10, 10, 13, 200, 10],
    'Cash': [1, 3, 1, 1, 1, 3, 1, 1],
    'EquityInvestments': [10, 10, 15, 10, 10, 10, 15, 10],
    'MoneyMarketInvestments': [20, 20, 20, 10, 20, 20, 20, 10],
    'Cluster': [0, 1, 1, 2, 0, 2, 1, 0]
}
df = pd.DataFrame(data)
  • 完成分组聚合,计算每个Cluster下的各类投资总规模
# 定义需要纳入堆叠展示的投资指标列
investment_cols = ['BondInvestments', 'Cash', 'EquityInvestments', 'MoneyMarketInvestments']
# 按Cluster分组,对各投资列求和
cluster_summary = df.groupby('Cluster')[investment_cols].sum()

Matplotlib原生实现(灵活度最高)

水平堆叠柱状图的核心实现逻辑是:每一段条形的绘制起点(对应barh的left参数)等于之前所有已绘制堆叠段的宽度总和,逐次累加偏移量即可完成堆叠效果。
实现代码如下:

# 创建画布
fig, ax = plt.subplots(figsize=(10, 6))
# 初始化堆叠的左侧偏移量,初始值为0
stack_left = pd.Series([0]*len(cluster_summary), index=cluster_summary.index)

# 逐列绘制堆叠段
for col in investment_cols:
    ax.barh(
        y=cluster_summary.index,  # y轴对应每个Cluster分组编号
        width=cluster_summary[col],  # 当前投资类别的累计金额
        left=stack_left,  # 堆叠的起始绘制位置
        label=col
    )
    # 更新下一层条形的起始位置
    stack_left += cluster_summary[col]

# 图表样式与可读性优化
ax.set_xlabel('累计投资金额')
ax.set_ylabel('聚类分组编号')
ax.set_title('不同聚类组的投资构成对比')
ax.set_yticks(cluster_summary.index)  # 固定y轴刻度为实际的Cluster值
ax.legend(bbox_to_anchor=(1.03, 1), loc='upper left')  # 将图例放置在图侧,避免遮挡条形
plt.tight_layout()  # 自动调整布局,避免标签被裁切
plt.show()

简化实现方案

如果不需要高度自定义图表细节,可直接使用Pandas内置的绘图接口(底层基于Matplotlib封装),无需手动计算堆叠偏移量,代码更简洁:

# Pandas内置水平堆叠柱状图实现
cluster_summary.plot(
    kind='barh',
    stacked=True,
    figsize=(10,6),
    title='不同聚类组的投资构成对比'
)
plt.xlabel('累计投资金额')
plt.ylabel('聚类分组编号')
plt.legend(bbox_to_anchor=(1.03, 1), loc='upper left')
plt.tight_layout()
plt.show()

如果需要更统一的美观视觉风格,可导入seaborn提前设置全局主题,所有后续绘图代码会自动套用风格:

import seaborn as sns
sns.set_theme(style="whitegrid")  # 在绘图代码前执行即可生效

内容的提问来源于stack exchange,提问作者coelidonum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.05 04:45:04