如何为DataFrame两列绘制堆叠柱状图?现有代码失效求解决
堆叠柱状图绘制解决方案
你想要基于给定的DataFrame绘制堆叠柱状图,核心需求是让对应列的柱子内部堆叠不同type的项,但原代码无法实现预期效果,下面给出问题分析和解决方案:
原代码问题分析
你写的代码两次调用df.plot()分别单独绘制单个列,还通过position设置了柱子的并列位置,这会导致两个问题:
stacked=True完全无效,因为单个列没有其他系列可以堆叠- 最终得到的是两组普通并列柱状图,而非你需要的堆叠效果
正确实现方式
根据你的数据结构(type分为A/B/C/D,数值列包含0error_prone_nodes、0others、1error_prone_nodes、1others),分两种常见需求给出解决方案:
需求1:每个Type对应两组堆叠柱(0组和1组)
每个type下显示两个并列柱子,分别对应0组和1组,每组柱子内部堆叠error_prone_nodes和others的数值:
import pandas as pd import matplotlib.pyplot as plt # 模拟你的数据(替换为真实DataFrame即可) data = { 'type': ['A', 'B', 'C', 'D'], '0error_prone_nodes': [10, 20, 15, 25], '0others': [5, 10, 8, 12], '1error_prone_nodes': [15, 25, 20, 30], '1others': [7, 12, 10, 15] } df = pd.DataFrame(data) fig, ax = plt.subplots(figsize=(10, 6)) # 绘制0组的堆叠柱 df.plot( x='type', y=['0error_prone_nodes', '0others'], kind='bar', stacked=True, ax=ax, width=0.4, position=0, color=['#1f77b4', '#ff7f0e'] ) # 绘制1组的堆叠柱,与0组并列 df.plot( x='type', y=['1error_prone_nodes', '1others'], kind='bar', stacked=True, ax=ax, width=0.4, position=1, color=['#2ca02c', '#d62728'] ) # 调整图表标签和图例 ax.set_xlabel('Type') ax.set_ylabel('数值') ax.legend( ['0组-错误节点', '0组-其他节点', '1组-错误节点', '1组-其他节点'], bbox_to_anchor=(1.05, 1), loc='upper left' ) plt.tight_layout() plt.show()
需求2:按组别(0/1)堆叠不同Type的数值
如果你的需求是x轴为0、1两个组别,每个组别下的柱子堆叠不同type的数值,可先重塑数据再绘图:
import pandas as pd import matplotlib.pyplot as plt # 模拟数据 data = { 'type': ['A', 'B', 'C', 'D'], '0error_prone_nodes': [10, 20, 15, 25], '0others': [5, 10, 8, 12], '1error_prone_nodes': [15, 25, 20, 30], '1others': [7, 12, 10, 15] } df = pd.DataFrame(data).set_index('type') # 拆分0组和1组数据,统一列名 df0 = df[['0error_prone_nodes', '0others']].rename(columns=lambda x: x[1:]) df1 = df[['1error_prone_nodes', '1others']].rename(columns=lambda x: x[1:]) # 合并为以组别为索引的DataFrame combined_df = pd.concat([df0.sum().rename('0'), df1.sum().rename('1')], axis=1).T fig, ax = plt.subplots(figsize=(10, 6)) combined_df.plot(kind='bar', stacked=True, ax=ax) ax.set_xlabel('组别') ax.set_ylabel('总数值') ax.legend(title='节点类型') plt.show()
内容的提问来源于stack exchange,提问作者maks
相关产品推荐
相关产品推荐

