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

如何使用pandas中的DataFrame绘制时间序列图

报错原因
  • 你使用的df.plot()传参错误,该方法默认需要传入列名字符串而非直接传入Series对象,另外你的Time列为字符串类型,没有被识别为时间格式,也会导致坐标轴展示异常
  • matplotlib的标签设置需要放在绘图命令之后,否则不会生效
最优实现方案

建议先将时间列转换为标准时间格式,保证时间轴刻度展示逻辑符合时间序列规范:

import pandas as pd
import matplotlib.pyplot as plt

# 读取数据
df = pd.read_csv('ApplianceShipments.csv')

# 把T1-1985这类季度标识转换为标准时间格式,T对应季度Q
df['Time'] = pd.PeriodIndex(df['Time'].str.replace('T', 'Q'), freq='Q').to_timestamp()

# 绘图
plt.figure(figsize=(10, 6))
plt.plot(df['Time'], df['Goods'], marker='o', color='#2c7fb8', linewidth=2)

# 配置图表样式
plt.xlabel('时间')
plt.ylabel('货物数量(单位:千)')
plt.xticks(rotation=45)
# 自动调整布局避免标签被截断
plt.tight_layout()
plt.show()
简化实现(保留原始时间字符串作为刻度)

如果你不需要时间轴的自动区间计算,直接用原始的T1-1985作为x轴刻度,可以直接用matplotlib的plot方法绘制:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('ApplianceShipments.csv')
plt.figure(figsize=(10, 6))
plt.plot(df['Time'], df['Goods'], marker='o')
plt.xlabel('时间')
plt.ylabel('货物数量(单位:千)')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:39:01