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

使用Pandas绘制TSLA股票数据时x轴时间戳触发TypeError求助

解决Matplotlib绘制Pandas MultiIndex日期轴的TypeError问题

我来帮你搞定这个问题!你遇到的报错根源是从Morningstar获取的DataFrame用了多层索引(MultiIndex)——它的索引是(股票代码, 时间戳)这样的元组,matplotlib没法直接把这种元组当作x轴的刻度值,这就是报错TypeError: ('TSLA', Timestamp('2018-01-01 00:00:00')) is not a string的原因。另外你找不到df1['Date']是因为日期并没有作为普通列存在,而是藏在多层索引的第二层里。

下面给你两种简单的解决方案:

方案1:重置索引,把日期转为普通列

直接用reset_index()把多层索引展开成列,这样日期就会出现在Date列中,之后直接用这个列作为x轴即可:

import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web

style.use('ggplot')
start = dt.datetime(2018, 1, 1)
end = dt.datetime(2018, 5, 24)
df1 = web.DataReader('TSLA', 'morningstar', start, end)
df1['100ma'] = df1['Open'].rolling(window=100).mean()

# 关键:重置索引,把日期提取为普通列
df1 = df1.reset_index()

ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1)
ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1)

# 现在用df1['Date']作为x轴
ax1.plot(df1['Date'], df1['Close'])
ax1.plot(df1['Date'], df1['100ma'])
ax2.bar(df1['Date'], df1['Volume'])

# 可选:旋转x轴标签避免重叠
plt.xticks(rotation=45)
plt.show()

方案2:直接替换索引为时间戳层(更简洁)

如果你不想新增列,可以直接把多层索引的第二层(时间戳)提取出来作为新的索引:

import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web

style.use('ggplot')
start = dt.datetime(2018, 1, 1)
end = dt.datetime(2018, 5, 24)
df1 = web.DataReader('TSLA', 'morningstar', start, end)
df1['100ma'] = df1['Open'].rolling(window=100).mean()

# 关键:提取多层索引的第二层(时间戳)作为新索引
df1.index = df1.index.get_level_values(1)

ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1)
ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1)

# 现在可以直接用df1.index作为x轴
ax1.plot(df1.index, df1['Close'])
ax1.plot(df1.index, df1['100ma'])
ax2.bar(df1.index, df1['Volume'])

plt.xticks(rotation=45)
plt.show()

补充说明:为什么单独画High/Close没问题?

你之前只绘制df1['High']和df1['Close']时,matplotlib默认会用行号作为x轴,根本没用到你的DataFrame索引,所以不会触发多层索引的格式问题。但一旦你显式指定x轴为df1.index,就会碰到元组格式的索引,导致报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:57:39