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

使用Matplotlib绘制趋势线时遇datetime类型错误求助

解决np.polyfit处理datetime对象时的类型错误

问题原因

你遇到的TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'float',核心原因是numpy的polyfit函数仅支持数值型输入,而你传入的date_list是datetime.datetime对象——numpy无法对这类时间对象执行浮点运算(比如函数内部的+0.0转换操作),因此触发了类型不兼容的错误。

解决方案

把datetime对象转换成matplotlib或numpy可识别的数值格式即可。最适配绘图场景的方法是使用matplotlib.dates.date2num()函数:它会把datetime对象转换为matplotlib内部用于日期表示的浮点数(代表从1970-01-01以来的天数),既满足polyfit的数值要求,绘图时又能自动还原为日期格式显示,无需额外调整坐标轴。

修改后的完整代码

import matplotlib.pyplot as plt
import pandas as pd
import datetime as dt
from datetime import datetime
import numpy as np
import matplotlib.pylab as plb

notes = pd.read_csv("tsla.csv")
notes.dropna(inplace=True)
date_list = notes['x']
price_list = notes['Close']
date_list = date_list.tolist()
price_list = price_list.tolist()

for i in range(len(date_list)):
    date_list[i] = (date_list[i][:-8])
    date_list[i] = date_list[i][:-5] + date_list[i][-3:-1]
    date_list[i] = datetime.strptime(date_list[i], "%m/%d/%y")

price_list = list(map(lambda x: int(x), price_list))

plt.plot(date_list, price_list)
plt.ylabel("Prices")
plt.xlabel("Dates")

# 新增:将datetime对象转换为matplotlib可识别的数值格式
x_num = plb.dates.date2num(date_list)
# 使用数值化的日期进行多项式拟合
z = np.polyfit(x_num, price_list, 1)
p = np.poly1d(z)
# 绘图时仍用原始datetime对象作为x轴,保证日期显示正常
plb.plot(date_list, p(x_num), "r--")

plt.show()

额外说明

  • 如果你偏好使用时间戳(从1970-01-01以来的秒数)转换,也可以这样实现:
    x_ts = [d.timestamp() for d in date_list]
    z = np.polyfit(x_ts, price_list, 1)
    p = np.poly1d(z)
    plb.plot(date_list, p(x_ts), "r--")
    
    但date2num更适配matplotlib的日期坐标轴,无需额外调整格式。
  • 原代码中plb.plot(x,p(x),"r--")的x是未定义变量,这也是潜在问题,修改后我们直接使用原始date_list作为x轴参数,确保趋势线与原始数据对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 20:02:30