python date2num_Python matplotlib.dates.date2num:将numpy数组转换为matplotlib日期时间

I am trying to plot a custom chart with datetime axis. My understanding is that matplotlib requires a float format which is days since epoch. So, I want to convert a numpy array to the float epoch as required by matplotlib.

The datetime values are stored in a numpy array called t:

In [235]: t

Out[235]: array(['2008-12-01T00:00:59.000000000-0800',

'2008-12-01T00:00:59.000000000-0800',

'2008-12-01T00:00:59.000000000-0800',

'2008-12-01T00:09:26.000000000-0800',

'2008-12-01T00:09:41.000000000-0800'], dtype='datetime64[ns]')

Apparently, matplotlib.dates.date2num only accepts a sequence of python datetimes as input (not numpy datetimes arrays):

import matplotlib.dates as dates

plt_dates = dates.date2num(t)

raises AttributeError: 'numpy.datetime64' object has no attribute 'toordinal'

How should I resolve this issue? I hope to have a solution that works for all types of numpy.datetime like object.

My best workaround (which I am not sure to be correct) is not to use date2num at all. Instead, I try to use the following:

z = np.array([0]).astype(t.dtype)

plt_dates = (t - z)/ np.timedelta64(1,'D')

Even, if this solution is correct, it is nicer to use library functions, instead of manual adhoc workarounds.

解决方案

For a quick fix, use:

import matplotlib.dates as dates

plt_dates = dates.date2num(t.to_pydatetime())

or:

import matplotlib.dates as dates

plt_dates = dates.date2num(list(t))

It seems the latest (matplotlib.__version__ '2.1.0') does not like numpy arrays... Edit: In my case, after checking the source code, the problem seems to be that the latest matplotlib.cbook cannot create an iterable from the numpy array and thinks the array is a number.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值