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

如何使用Pandas绘制含三类部门数据的时间序列图表

多层索引DataFrame绘制部门趋势图的高效方法

你不需要拆分DataFrame再叠加绘图,用Pandas的unstack方法把多层索引转换为宽格式后,可以直接快速绘制线图或柱状图,每个部门自动对应一条曲线/一组柱子。

步骤1:构造/加载数据

先还原你的多层索引DataFrame(如果已有数据可跳过此步):

import pandas as pd
import matplotlib.pyplot as plt

# 构造示例数据
data = [
    ('2019-01', 'Sales', 120),
    ('2019-01', 'Engineering', 461),
    ('2019-01', 'Support', 42),
    ('2019-02', 'Sales', 92),
    ('2019-02', 'Engineering', 428),
    ('2019-02', 'Support', 53),
    ('2019-03', 'Sales', 95),
    ('2019-03', 'Engineering', 492),
    ('2019-03', 'Support', 57),
    ('2019-04', 'Sales', 121),
    ('2019-04', 'Engineering', 498),
    ('2019-04', 'Support', 58),
    ('2019-05', 'Sales', 119),
    ('2019-05', 'Engineering', 497),
    ('2019-05', 'Support', 59),
    ('2019-06', 'Sales', 89),
    ('2019-06', 'Engineering', 423),
    ('2019-06', 'Support', 40),
    ('2019-07', 'Sales', 95),
    ('2019-07', 'Engineering', 379),
    ('2019-07', 'Support', 63),
]

df = pd.DataFrame(data, columns=['Month', 'Department', 'Count'])
df = df.set_index(['Month', 'Department'])

步骤2:转换为宽格式

用unstack将Department层级转为列,让每个部门对应一列数据,月份作为索引:

# 转换为宽格式,Department成为列
df_wide = df.unstack(level='Department')
# 移除多余的列层级(unstack后列是多层结构,这里简化为部门名称)
df_wide.columns = df_wide.columns.droplevel(0)

转换后的df_wide结构如下:

Department  Sales  Engineering  Support
Month                                  
2019-01       120          461       42
2019-02        92          428       53
2019-03        95          492       57
2019-04       121          498       58
2019-05       119          497       59
2019-06        89          423       40
2019-07        95          379       63

步骤3:绘制图表

线图(展示趋势)

用Pandas内置绘图一键生成,每个部门自动对应一条曲线:

df_wide.plot(kind='line', figsize=(10, 6), marker='o')
plt.title('各部门月度计数趋势')
plt.xlabel('月份')
plt.ylabel('计数')
plt.xticks(rotation=45)  # 旋转月份标签避免重叠
plt.tight_layout()  # 自动调整布局
plt.show()

也可以用Matplotlib手动绘制,灵活性更高:

plt.figure(figsize=(10, 6))
for dept in df_wide.columns:
    plt.plot(df_wide.index, df_wide[dept], marker='o', label=dept)

plt.title('各部门月度计数趋势')
plt.xlabel('月份')
plt.ylabel('计数')
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

柱状图(展示对比)

分组柱状图(月度内部门对比)

df_wide.plot(kind='bar', figsize=(10, 6))
plt.title('各部门月度计数对比')
plt.xlabel('月份')
plt.ylabel('计数')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

堆叠柱状图(月度总计数及部门占比)

df_wide.plot(kind='bar', stacked=True, figsize=(10, 6))
plt.title('各部门月度计数堆叠对比')
plt.xlabel('月份')
plt.ylabel('总计数')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 02:00:32