如何在Pandas中实现按ID分组的分隔式堆叠条形图?
分组堆叠条形图代码修正方案
原始数据与需求
数据定义
import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame( { 'ID': ['ID001', 'ID002', 'ID003'], 'RUNNING': [5, 6, 3], 'QUEUE': [1, 2, 5], 'FINISHED': [6, 2, 4], 'PROCESSED': [2, 6, 4], } )
对应数据表格:
| ID | RUNNING | QUEUE | FINISHED | PROCESSED | |
|---|---|---|---|---|---|
| 0 | ID001 | 5 | 1 | 6 | 2 |
| 1 | ID002 | 6 | 2 | 2 | 6 |
| 2 | ID003 | 3 | 5 | 4 | 4 |
需求
为每个ID创建分组堆叠条形图,每组包含两个堆叠条形:
- 运行任务组:堆叠
RUNNING和QUEUE数据 - 完成任务组:堆叠
FINISHED和PROCESSED数据
原始代码问题
原始代码存在三个问题:
- x轴刻度未显示ID名称
- 每组堆叠条形之间无间距
- 图表左侧被截断
原始代码
running = df[['RUNNING', 'QUEUE']] finished = df[['FINISHED', 'PROCESSED']] fig, ax = plt.subplots(figsize=(7, 3)) running.plot( kind='bar', stacked=True, ax=ax, use_index=True, color={'RUNNING': 'orange', 'QUEUE': 'yellow'}, edgecolor='black', position=1, ) finished.plot( kind='bar', stacked=True, ax=ax, use_index=True, color={'FINISHED': 'green', 'PROCESSED': 'blue'}, edgecolor='black', position=0, ) fig.tight_layout() plt.show()
修正后的代码
import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame( { 'ID': ['ID001', 'ID002', 'ID003'], 'RUNNING': [5, 6, 3], 'QUEUE': [1, 2, 5], 'FINISHED': [6, 2, 4], 'PROCESSED': [2, 6, 4], } ) # 定义条形宽度与x轴基础位置 bar_width = 0.35 x = range(len(df)) fig, ax = plt.subplots(figsize=(7, 3)) # 绘制运行任务组的堆叠条形 running_bottom = 0 for col in ['RUNNING', 'QUEUE']: ax.bar( [i - bar_width/2 for i in x], df[col], width=bar_width, bottom=running_bottom, color={'RUNNING': 'orange', 'QUEUE': 'yellow'}[col], edgecolor='black', label=col ) running_bottom += df[col] # 绘制完成任务组的堆叠条形 finished_bottom = 0 for col in ['FINISHED', 'PROCESSED']: ax.bar( [i + bar_width/2 for i in x], df[col], width=bar_width, bottom=finished_bottom, color={'FINISHED': 'green', 'PROCESSED': 'blue'}[col], edgecolor='black', label=col ) finished_bottom += df[col] # 设置x轴刻度为ID名称 ax.set_xticks(x) ax.set_xticklabels(df['ID']) # 调整布局解决截断问题,外置图例避免挤压 fig.tight_layout() ax.legend(loc='upper right', bbox_to_anchor=(1.15, 1)) plt.show()
修正说明
- 显示ID名称:通过
ax.set_xticks(x)指定刻度位置,ax.set_xticklabels(df['ID'])替换刻度文本为ID值。 - 添加组间距:自定义条形宽度,将两组条形分别向左右偏移半个宽度,x轴使用连续整数作为基础位置,自然形成组间空隙。
- 解决左侧截断:
fig.tight_layout()自动调整图表边距,同时将图例放置在图表外侧,避免占用绘图区域导致内容截断。
内容的提问来源于stack exchange,提问作者VERBOSE
相关产品推荐
相关产品推荐

