在x轴上具有索引的散点图形式数据框

Koc*_*r4d 8 python matplotlib pandas

我有大熊猫DataFramedfindex命名date和列columnAcolumnBcolumnC

我正在尝试使用语法将图散布index在x轴和columnAy轴上DataFrame

当我尝试:

df.plot(kind='scatter', x='date', y='columnA')

KeyError: 'date'可能会收到一个错误,可能是因为date不是列

df.plot(kind='scatter', y='columnA')

我可能会收到一个错误,ValueError: scatter requires and x and y column因此X轴上没有默认索引。

df.plot(kind='scatter', x=df.index, y='columnA')

我出错了KeyError: "DatetimeIndex(['1818-01-01', '1818-01-02', '1818-01-03', '1818-01-04',\n '1818-01-05', '1818-01-06', '1818-01-07', '1818-01-08',\n '1818-01-09', '1818-01-10',\n ...\n '2018-03-22', '2018-03-23', '2018-03-24', '2018-03-25',\n '2018-03-26', '2018-03-27', '2018-03-28', '2018-03-29',\n '2018-03-30', '2018-03-31'],\n dtype='datetime64[ns]', name='date', length=73139, freq=None) not in index"


如果matplotlib.pyplot直接使用我可以画出来

plt.scatter(df.index, df['columnA'])

有没有一种方法可以x-axis使用DataFrame kind语法来绘制索引?

小智 10

至少pandas>1.4最简单的是:

df['columnA'].plot(style=".")
Run Code Online (Sandbox Code Playgroud)

这使您可以混合散点图和线图,以及使用标准 pandas 绘图界面


小智 8

一个更简单的解决方案是:

df['x1'] = df.index
Run Code Online (Sandbox Code Playgroud)
df.plot(kind='scatter', x='x1', y='columnA')
Run Code Online (Sandbox Code Playgroud)

只需在 plot 语句之外创建索引变量。


Ami*_*ory 7

这有点丑陋(我认为您在问题中使用的matplotlib解决方案更好,FWIW),但是您始终可以使用索引作为列usinng创建一个临时DataFrame

df.reset_index()
Run Code Online (Sandbox Code Playgroud)

如果索引是无名的,则默认名称为'index'。假设是这种情况,您可以使用

df.reset_index().plot(kind='scatter', x='index', y='columnA')
Run Code Online (Sandbox Code Playgroud)

  • @Kocur4d 谢谢。仅供参考:索引*不必*必须是唯一的:`pd.DataFrame({'a': [1, 2]}, index=[1, 1])` 很好。我怀疑 Pandas 中缺乏对索引分散的支持更多是一种疏忽。 (2认同)