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

如何用Matplotlib绘制嵌套字典数据的堆叠条形图

用Matplotlib绘制堆叠条形图:处理嵌套字典数据

第一步:拆分嵌套字典数据

先把你的嵌套字典拆分成Matplotlib需要的独立数组:

  • 提取X轴的性别标签
  • 分别提取每个性别的"Yes"和"No"计数

代码实现:

# 你的原始数据
data = {
    'Female': {'Yes': 34, 'No': 4},
    'Male': {'Yes': 59, 'No': 4},
    'Other': {'Yes': 5, 'No': 0}
}

# 提取X轴的性别标签
genders = list(data.keys())

# 提取"Yes"的计数数组
yes_counts = [gender_data['Yes'] for gender_data in data.values()]

# 提取"No"的计数数组
no_counts = [gender_data['No'] for gender_data in data.values()]

第二步:绘制堆叠条形图

利用Matplotlib的bar方法,通过bottom参数实现堆叠效果:先画"Yes"的条形作为底层,再把"No"的条形堆叠在它上方。

完整代码:

import matplotlib.pyplot as plt

# 生成X轴的位置索引(Matplotlib的bar方法默认需要数值型X轴)
x = range(len(genders))
width = 0.5  # 条形宽度

# 绘制底层的"Yes"条形
plt.bar(x, yes_counts, width, label='Yes')

# 绘制堆叠在上方的"No"条形,用bottom参数指定底部对齐位置
plt.bar(x, no_counts, width, bottom=yes_counts, label='No')

# 将X轴的数值索引替换为实际性别标签
plt.xticks(x, genders)

# 添加图例、标题和Y轴标签
plt.legend()
plt.title('Gender vs Response Count')
plt.ylabel('Number of Responses')

# 显示图形
plt.show()

关键说明

  • bottom=yes_counts是堆叠效果的核心:它让"No"条形的底部对齐到对应性别"Yes"条形的顶部。
  • 用range(len(genders))生成X轴位置,是因为Matplotlib的bar方法优先接受数值型坐标,之后再通过plt.xticks替换成可读性更强的性别标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:07:18