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

Python子图绘制报错:TypeError:DataFrame对象无法解析为整数

解决Python双子图绘制的TypeError问题

错误原因

你代码里的df[index]写法存在问题:

  • 若想调用DataFrame的datetime索引,正确写法是df.index,而非df[index]
  • 若index是你自定义的变量,该变量大概率被错误赋值为DataFrame类型,而matplotlib的plot函数要求x参数为一维序列(如数组、Series),传入DataFrame就会触发TypeError: 'DataFrame' object cannot be interpreted as an integer

修正后的代码

方式1:利用pandas自动映射索引为x轴(推荐)

import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

# 直接传入列数据,自动使用datetime索引作为x轴
ax1.plot(df['Data1'], color='tab:blue')
ax2.plot(df['Data2'], color='tab:orange')

# 添加标签优化图表可读性
ax1.set_xlabel('日期')
ax1.set_ylabel('Data1', color='tab:blue')
ax2.set_ylabel('Data2', color='tab:orange')

plt.xticks(rotation=45)  # 旋转日期标签避免重叠
plt.show()

方式2:显式指定x轴为datetime索引

import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

# 显式传入索引作为x轴
ax1.plot(df.index, df['Data1'], color='tab:blue')
ax2.plot(df.index, df['Data2'], color='tab:orange')

# 添加标签优化图表可读性
ax1.set_xlabel('日期')
ax1.set_ylabel('Data1', color='tab:blue')
ax2.set_ylabel('Data2', color='tab:orange')

plt.xticks(rotation=45)  # 旋转日期标签避免重叠
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 19:01:13