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

如何为指定DataFrame生成x轴为A-F列的堆叠条形图(Stacked bar plot)

堆叠条形图实现方案

数据准备与绘图代码

将表格数据转换为DataFrame后,使用Matplotlib绘制符合要求的堆叠条形图,代码如下:

import pandas as pd
import matplotlib.pyplot as plt

# 构建对应数据
data = {
    'Percentage': ['0%', '10%', '50%', '100%'],
    'A': [10, 89, 87, 89],
    'B': [20, 87, 876, 78],
    'C': [50, 65, 89, 89],
    'D': [60, 87, 978, 89],
    'E': [100, 89, 6, 54],
    'F': [90, 88, 0, 34]
}
df = pd.DataFrame(data).set_index('Percentage')

# 转置数据,让X轴对应A-F类别
df_transposed = df.T

# 绘制堆叠条形图
plt.figure(figsize=(10, 6))
df_transposed.plot(kind='bar', stacked=True, ax=plt.gca())

# 设置图表属性
plt.xlabel('类别')
plt.ylabel('数值')
plt.title('各百分比对应数值堆叠条形图')
plt.legend(title='百分比')

plt.tight_layout()
plt.show()

效果说明

运行代码后生成的图表完全匹配需求:

  • X轴为A、B、C、D、E、F六个类别
  • 每个类别下的堆叠条由四个分段组成,分别对应0%、10%、50%、100%对应的数值
  • 图例标注各分段对应的百分比,清晰区分不同部分

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:35:58