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

如何遍历DataFrame分组并为每个场所分组生成收支时间序列条形图?

正确实现代码

首先把Month列转为时间友好的格式方便X轴展示:

import pandas as pd
import matplotlib.pyplot as plt

# 初始化数据
data = [{'Month': '2020-01-01', 'Expense':1000, 'Revenue':5000, 'Building':'Stadium'}, 
       {'Month': '2020-02-01', 'Expense':3000, 'Revenue':4000, 'Building':'Stadium'},
       {'Month': '2020-03-01', 'Expense':7000, 'Revenue':5000, 'Building':'Stadium'}, 
       {'Month': '2020-04-01', 'Expense':3000, 'Revenue':4000, 'Building':'Stadium'},
       {'Month': '2020-01-01', 'Expense':5000, 'Revenue':6000, 'Building':'Casino'}, 
       {'Month': '2020-02-01', 'Expense':5000, 'Revenue':4000, 'Building':'Casino'},
       {'Month': '2020-03-01', 'Expense':5000, 'Revenue':9000, 'Building':'Casino'},
       {'Month': '2020-04-01', 'Expense':6000, 'Revenue':10000, 'Building':'Casino'}]
df = pd.DataFrame(data)
# 格式化月份列,避免X轴展示冗余信息
df['Month'] = pd.to_datetime(df['Month']).dt.strftime('%Y-%m')

方案1:所有场所子图并排展示,支持切换堆叠/并列

修改stacked参数即可切换展示模式:False为并列条形图,True为堆叠条形图

grouped = df.groupby('Building')
group_count = len(grouped)
# 创建和分组数量匹配的子图
fig, axes = plt.subplots(1, group_count, figsize=(14, 4), sharey=True)
# 控制是否堆叠
stacked = False

for idx, (building_name, group_df) in enumerate(grouped):
    ax = axes[idx]
    group_df.plot(
        x='Month', 
        y=['Expense', 'Revenue'], 
        kind='bar', 
        stacked=stacked,
        ax=ax,
        color=['#f8766d', '#00bfc4']
    )
    ax.set_title(f'{building_name} 收支情况')
    ax.set_xlabel('月份')
    ax.set_ylabel('金额')
    ax.tick_params(axis='x', rotation=0)

plt.tight_layout()
plt.show()

方案2:每个场所生成独立的单独图表

stacked = False
grouped = df.groupby('Building')

for building_name, group_df in grouped:
    plt.figure(figsize=(8,4))
    group_df.plot(
        x='Month', 
        y=['Expense', 'Revenue'], 
        kind='bar', 
        stacked=stacked,
        color=['#f8766d', '#00bfc4']
    )
    plt.title(f'{building_name} 收支情况')
    plt.xlabel('月份')
    plt.ylabel('金额')
    plt.xticks(rotation=0)
    plt.tight_layout()
    plt.show()

原代码错误点说明

  • 初始化子图时仅创建了1个子图,无法匹配多个分组的展示需求
  • 循环绘图时调用全局df而非分组后的group数据,同时错误将Month作为行索引取值
  • 需求是收支条形图,却调用了直方图hist方法,和预期展示效果不符
  • set_title格式化时没有传入场所名称变量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:36:02