在x轴上具有索引的散点图形式数据框 [英] Scatter plot form dataframe with index on x-axis
问题描述
我有熊猫DataFrame
,df
,名为date
的index
和列columnA
,columnB
和columnC
I've got pandas DataFrame
, df
, with index
named date
and the columns columnA
, columnB
and columnC
我正在尝试使用DataFrame
语法将图index
散布在x轴上,将columnA
散布在y轴上.
I am trying to scatter plot index
on a x-axis and columnA
on a y-axis using the DataFrame
syntax.
当我尝试时:
df.plot(kind='scatter', x='date', y='columnA')
我可能会收到错误KeyError: 'date'
,可能是因为date
不是列
I ma getting an error KeyError: 'date'
probably because the date
is not column
df.plot(kind='scatter', y='columnA')
我遇到错误:
ValueError: scatter requires and x and y column
因此在x轴上没有默认索引.
so no default index on x-axis.
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
,我可以绘制它
I can plot it if I use matplotlib.pyplot
directly
plt.scatter(df.index, df['columnA'])
是否可以使用DataFrame
kind
语法将索引绘制为x-axis
?
Is there a way to plot index as x-axis
using the DataFrame
kind
syntax?
推荐答案
这有点丑陋(我认为您在问题中使用的matplotlib解决方案更好,FWIW),但是您始终可以使用索引创建一个临时DataFrame作为列
This is kind of ugly (I think the matplotlib solution you used in your question is better, FWIW), but you can always create a temporary DataFrame with the index as a column usinng
df.reset_index()
如果索引是无名的,则默认名称将为'index'
.假设是这种情况,您可以使用
If the index was nameless, the default name will be 'index'
. Assuming this is the case, you could use
df.reset_index().plot(kind='scatter', x='index', y='columnA')
这篇关于在x轴上具有索引的散点图形式数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!