如何用Pandas、Matplotlib绘制以loc/items为x轴的堆叠柱状图
实现反向堆叠柱状图的方法
核心思路是先将原始DataFrame的结构调整为行对应loc/items,列对应各个Name,再绘制堆叠柱状图,无需手动构造数据。
步骤1:明确原始DataFrame结构
假设你的原始数据实际结构如下(修正列名格式,loc.items是两列loc和items):
| Names | loc | items |
|---|---|---|
| Name1 | 343 | 1756 |
| Name2 | 5 | 15 |
| ... | ... | ... |
| Name99 | 22 | 111 |
步骤2:数据转换与绘图代码
用pandas的索引设置和转置操作自动调整结构,再调用绘图方法:
import pandas as pd import matplotlib.pyplot as plt # 1. 构造/读取原始DataFrame(示例模拟你的数据) data = { 'Names': [f'Name{i}' for i in range(1, 100)], 'loc': [343, 5, 688, 88, 1] + [10]*94 + [22], 'items': [1756, 15, 1667, 444, 1] + [20]*94 + [111] } df = pd.DataFrame(data) # 2. 将Names设为索引后转置,得到所需结构 df_transposed = df.set_index('Names').T # 3. 绘制堆叠柱状图 df_transposed.plot(kind='bar', stacked=True, figsize=(10, 6)) plt.title('loc/items的各Name数值堆叠柱状图') plt.xlabel('类别') plt.ylabel('数值') # 把图例移到图外避免遮挡 plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.tight_layout() plt.show()
之前代码无效的原因
你之前的代码存在两个关键问题:
- 错误指定
x='carrier',但你的数据中不存在carrier列; - 未对数据转置,原始结构是行对应Name,列对应loc/items,无法直接生成以loc/items为x轴的堆叠柱。
转置后的df_transposed和你手动构造的DataFrame结构完全一致,因此能直接生成符合需求的堆叠图。
内容的提问来源于stack exchange,提问作者Jodahsh
相关产品推荐
相关产品推荐

