pandas 在 x 轴上带有索引的散点图表单数据框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49834883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scatter plot form dataframe with index on x-axis
提问by Kocur4d
I've got pandas DataFrame
, df
, with index
named date
and the columns columnA
, columnB
and columnC
我有 Pandas DataFrame
, df
, , , ,index
命名date
和列columnA
,columnB
和columnC
I am trying to scatter plot index
on a x-axis and columnA
on a y-axis using the DataFrame
syntax.
我正在尝试使用语法index
在 x 轴和columnA
y 轴上散点图DataFrame
。
When I try:
当我尝试:
df.plot(kind='scatter', x='date', y='columnA')
I ma getting an error KeyError: 'date'
probably because the date
is not column
我收到错误KeyError: 'date'
可能是因为date
不是列
df.plot(kind='scatter', y='columnA')
I am getting an error:
我收到一个错误:
ValueError: scatter requires and x and y column
so no default index on x-axis.
所以 x 轴上没有默认索引。
df.plot(kind='scatter', x=df.index, y='columnA')
I am getting error
我收到错误
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"
I can plot it if I use matplotlib.pyplot
directly
如果我matplotlib.pyplot
直接使用,我可以绘制它
plt.scatter(df.index, df['columnA'])
Is there a way to plot index as x-axis
using the DataFrame
kind
syntax?
有没有办法像x-axis
使用DataFrame
kind
语法一样绘制索引?
采纳答案by Ami Tavory
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
这有点难看(我认为您在问题中使用的 matplotlib 解决方案更好,FWIW),但您始终可以使用索引作为列创建临时 DataFrame
df.reset_index()
If the index was nameless, the default name will be 'index'
. Assuming this is the case, you could use
如果索引是无名的,则默认名称将为'index'
. 假设是这种情况,您可以使用
df.reset_index().plot(kind='scatter', x='index', y='columnA')