散点图形式数据框,索引在x轴上

时间:2018-04-14 18:36:37

标签: python pandas matplotlib

我有大熊猫DataFramedfindex名为date,列columnAcolumnB和{{1 }}

我正在尝试使用columnC语法在x轴上散布index,在y轴上散布columnA

当我尝试:

DataFrame

我收到错误df.plot(kind='scatter', x='date', y='columnA')可能是因为KeyError: 'date'不是列

date

我收到错误df.plot(kind='scatter', y='columnA')因此在x轴上没有默认索引。

ValueError: scatter requires and x and y column

我收到错误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

2 个答案:

答案 0 :(得分:4)

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

df.reset_index()

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

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

答案 1 :(得分:1)

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

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

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

相关问题