matplotlib在pandas DataFrame中绘制日期时间

Kev*_*son 15 python matplotlib pandas

我有一个像这样的pandas DataFrame training.head()

在此输入图像描述

DataFrame已按日期排序.我想制作一个散点图,其中广告系列的日期位于x轴上,成功率位于y轴上.我能够通过使用得到一个折线图training.plot(x='date',y='rate').但是,当我改变它时,training.plot(kind='scatter',x='date',y='rate')我得到一个错误:KeyError:你没有名为date'的项目

当我尝试制作散点图时,为什么我的索引列会消失?另外,我打赌我需要对那个日期字段做一些事情,这样它就不会像简单的字符串一样对待,不是吗?

额外的功劳,如果我希望每个帐号用不同的颜色绘制,我该怎么办?

Tom*_*ger 11

如果我没记错的话,绘图代码只考虑数字列.在内部它只选择数字列,这就是你得到键错误的原因.

什么是dtype date?如果是a datetime64,您可以将其重新命名为np.int64:

df['date_int'] = df.date.astype(np.int64)
Run Code Online (Sandbox Code Playgroud)

然后你是情节.

对于颜色部分,制作一个字典{account number: color}.例如:

color_d = {1: 'k', 2: 'b', 3: 'r'}
Run Code Online (Sandbox Code Playgroud)

然后当你绘图:

training.plot(kind='scatter',x='date',y='rate', color=df.account.map(color_d))
Run Code Online (Sandbox Code Playgroud)

  • `pd.to_datetime(df.date)` 可能有效。“-0400”是时区吗? (2认同)

Mar*_*kNS 8

我发现更改style折线图更简单,不包括连接线:

cb_df.plot(figsize=(16, 6), style='o')

在此输入图像描述

  • 我相信这与散点图不同 - 这就像使用虚线一样.这些点总是均匀间隔的,并不一定对应于原始数据值. (2认同)