KeyError: "DatetimeIndex(['2006-12-31', '2007-12-31'],\n dtype='datetime64[ns]', name='date', freq=None) not in index

KeyError: "DatetimeIndex(['2006-12-31', '2007-12-31'],\n dtype='datetime64[ns]', name='date', freq=None) not in index

我第一次使用 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]' 中发现了类似的问题。但这并没有解决我的问题。

我发现我做错了。我需要通过列名定义 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()