You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中基于给定列表绘制堆叠柱状图

绘制堆叠柱状图的实现方案

嗨,基于你提供的集群数据,我来给你展示如何用Python的matplotlib(最常用的绘图库)快速画出堆叠柱状图。下面是完整的步骤和代码:

步骤1:准备数据并导入库

首先我们需要把你的数据整理好,同时导入需要的库:

import matplotlib.pyplot as plt
import numpy as np

# 你的原始数据
Clusters = ['Cluster1', 'Cluster2', 'Cluster3', 'Cluster4', 'Cluster5', 'Cluster6', 'Cluster7']
clusterpoints = [
    [0, 2, 0, 5, 1, 0, 0, 0, 6, 0],
    [0, 0, 5, 0, 0, 5, 1, 0, 1, 0],
    [3, 0, 0, 1, 0, 6, 2, 0, 0, 0],
    [1, 4, 0, 1, 0, 0, 0, 1, 2, 1],
    [0, 2, 0, 5, 1, 0, 0, 0, 6, 0],
    [0, 0, 5, 0, 0, 5, 1, 0, 1, 0],
    [3, 0, 0, 1, 0, 6, 2, 0, 0, 0]
]
xaxispoints = ['V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10']

步骤2:绘制堆叠柱状图

核心思路是循环每个变量(V1-V10),依次在每个集群的柱子上堆叠对应的数值,关键是用bottom参数控制每个部分的起始高度:

# 设置x轴的位置(7个集群对应7个位置)
x = np.arange(len(Clusters))
# 每个柱子的宽度
width = 0.6

# 初始化底部高度,初始为0
bottom = np.zeros(len(Clusters))

# 循环每个变量,绘制堆叠部分
for idx, var in enumerate(xaxispoints):
    # 获取当前变量在所有集群中的数值
    values = [row[idx] for row in clusterpoints]
    # 绘制柱状图,bottom参数指定当前部分的起始高度
    plt.bar(x, values, width, label=var, bottom=bottom)
    # 更新底部高度,为下一个变量的堆叠做准备
    bottom += values

# 设置图表标签和标题
plt.title('Cluster Variable Distribution (Stacked Bar Chart)')
plt.xlabel('Clusters')
plt.ylabel('Values')
# 设置x轴刻度为集群名称
plt.xticks(x, Clusters)
# 添加图例(因为变量多,把图例放在图表右侧外面)
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
# 调整布局,防止图例被截断
plt.tight_layout()

# 显示图表
plt.show()

补充:用Pandas简化绘制

如果你习惯用pandas,可以把数据转成DataFrame,然后直接调用plot方法,代码更简洁:

import pandas as pd

# 转成DataFrame
df = pd.DataFrame(clusterpoints, index=Clusters, columns=xaxispoints)
# 绘制堆叠柱状图
df.plot(kind='bar', stacked=True, figsize=(10,6))
plt.title('Cluster Variable Distribution (Stacked Bar Chart)')
plt.xlabel('Clusters')
plt.ylabel('Values')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.tight_layout()
plt.show()

这样运行后,你就能得到每个集群由V1-V10数值堆叠而成的柱状图,每个颜色对应一个变量,清晰展示每个集群内部的变量分布情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:34:07