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

跟随教程用Matplotlib与Pandas绘图触发TypeError错误求助

问题分析与解决办法

首先,你的报错根源在于多余的plt.plot(plot1)调用,我来给你拆解一下原因:

  • 当你执行crimes_count_date.rolling(365).sum().plot(...)时,pandas已经帮你完成了所有子图的绘制工作,这个方法返回的plot1是一个存储着所有子图Axes对象的numpy数组,它不是可以直接用来绘图的数值数据。
  • 你后续调用plt.plot(plot1),相当于试图把Axes对象当作绘图数据传入,matplotlib自然无法把Axes对象转换成绘制折线需要的数值类型,这就触发了TypeError: float() argument must be a string or a number错误。

修正后的代码

只需要删掉那行多余的plt.plot(plot1)就可以正常运行了:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from reader import df_final

crimes_count_date = df_final.pivot_table('ID', aggfunc=np.size, columns='Primary Type', index=df_final.index.date, fill_value=0)
crimes_count_date.index = pd.DatetimeIndex(crimes_count_date.index)
# pandas的plot方法已经完成绘图,返回的是Axes数组,无需额外调用plt.plot
crimes_count_date.rolling(365).sum().plot(figsize=(12, 30), subplots=True, layout=(-1, 3), sharex=False, sharey=False)
plt.show()

额外的小建议

如果之后你想对生成的子图做个性化调整(比如修改标题、坐标轴标签),可以遍历plot1数组里的Axes对象来操作,举个例子:

plot1 = crimes_count_date.rolling(365).sum().plot(figsize=(12, 30), subplots=True, layout=(-1, 3), sharex=False, sharey=False)
# 遍历所有子图修改样式
for ax in plot1.flatten():
    ax.set_title(ax.get_title().replace('Primary Type: ', ''))
    ax.set_ylabel('Annual Rolling Count')
plt.show()

另外也可以先打印crimes_count_date.rolling(365).sum().head(),确认滚动求和后的数据是否符合预期,避免数据本身异常导致绘图问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:28:28