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

如何用Pandas和Matplotlib按Code分组绘制DateTime-Value折线图

多Code分组折线图绘制解决方案

问题场景

有一个包含3列、近80万行的DataFrame,需要绘制X轴为Datetime、Y轴为Value的折线图,要求为6种不同的Code各绘制一条单独的折线(各Code对应的数据长度不同不影响),但直接绘图的结果不符合预期。

修正后的示例DataFrame

原示例代码中Datetime列的写法会被解析为整数(如2022-03-29会计算为1990),需先修正为日期格式:

import pandas as pd

# 初始化数据
data = {
    'Code': ['AABB', 'AABC', 'AABB', 'AABC', 'AABD', 'AABC', 'AABB', 'AABC'],
    'Value': [1, 1, 2, 2, 1, 3, 3, 4],
    'Datetime': ['2022-03-29', '2022-03-29', '2022-03-30', '2022-03-30', 
                 '2022-03-30', '2022-03-31', '2022-03-31', '2022-03-31']
}

# 创建DataFrame并转换日期列类型
df = pd.DataFrame(data)
df['Datetime'] = pd.to_datetime(df['Datetime'])

原代码问题分析

你尝试的代码plt.plot(df["DateTime"], df["value"],...)存在两个核心问题:

  1. 列名大小写不匹配:原DataFrame日期列是Datetime、数值列是Value,代码中写了DateTime和value
  2. 未按Code分组:所有数据点被混在一起绘制,无法区分不同Code的折线

可行解决方案

方法1:Groupby分组逐组绘制

适合数据量大的场景,可灵活控制每个Code的样式:

import matplotlib.pyplot as plt

# 设置画布大小
plt.figure(figsize=(12, 6))

# 按Code分组遍历
for code, group in df.groupby('Code'):
    # 按日期排序,确保折线顺序正确
    sorted_group = group.sort_values('Datetime')
    plt.plot(sorted_group['Datetime'], sorted_group['Value'], label=code, marker='o', alpha=0.7)

# 添加图表标注
plt.xlabel('日期时间')
plt.ylabel('数值')
plt.title('不同Code的数值趋势')
plt.legend()
plt.xticks(rotation=45)  # 旋转X轴标签避免重叠
plt.tight_layout()  # 自动调整布局
plt.show()

方法2:透视表简化绘图

如果同一Code和Datetime组合无重复数据,或可接受聚合(如取均值),可以用透视表快速绘图:

# 生成透视表:行=日期,列=Code,值=Value;有重复项时可添加aggfunc='mean'做聚合
df_pivot = df.pivot(index='Datetime', columns='Code', values='Value')

# 直接绘制,pandas自动为每个Code生成折线
df_pivot.plot(figsize=(12, 6), marker='o', alpha=0.7)
plt.xlabel('日期时间')
plt.ylabel('数值')
plt.title('不同Code的数值趋势')
plt.legend(title='Code')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

关键注意事项

  • 必须确保Datetime列是datetime类型,否则X轴会按非时间顺序排列
  • 80万行数据量较大,建议先清理重复/异常值,必要时按时间间隔聚合采样,提升绘图效率
  • 分组后务必按Datetime排序,避免因数据顺序混乱导致折线显示异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:15:36