首页 > 解决方案 > KeyError: "DatetimeIndex(['2006-12-31', '2007-12-31'],\n dtype='datetime64[ns]', name='date', freq=None) 不在索引中

问题描述

我第一次使用 matplotlib 在条形图、柱形图、折线图和散点图中可视化我的数据。每当我提到 x 和 y 轴时,我都会收到错误消息。这是我下面所有图表的代码,

df.plot.bar(pd.DatetimeIndex(df['date']), y=df[value])
df.plot.bar(pd.DatetimeIndex(df['date']), y=df[value])
df.plot.line(pd.DatetimeIndex(df['date']), y=df[value])
df.plot.scatter(x=pd.DatetimeIndex(df['date']), y=df[value])
plt.show()

我在datetime index KeyError: 'the label [2000-01-03 00:00:00] is not in the [index]'中发现了类似的问题。但这并不能解决我的问题。

标签: python-3.xmatplotlibdatavisualization.toolkit

解决方案


我发现我做错了什么。我需要通过列名定义 x 和 y 轴,而无需提及df['date']但是,我已经使用scatter_matrix可视化了散点图。所以可行的代码是,

df.plot.bar(pd.DatetimeIndex(x='date', y='value')
df.plot.bar(pd.DatetimeIndex(x='date', y='value')
df.plot.line(pd.DatetimeIndex(x='date', y='value')
scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal='kde')
plt.show()

推荐阅读