简体   繁体   English

matplotlib中的日期时间图问题

[英]Problems with datetime plot in matplotlib

I am trying to plot some datetime data but I have two problems I can't solve. 我正在尝试绘制一些日期时间数据,但是我有两个无法解决的问题。 My code is the following: 我的代码如下:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime as DT
import numpy as np

%matplotlib inline

dt = np.dtype([('date', 'datetime64[D]'), ('count', np.uint32)])
data = np.array([(np.datetime64('2014-12-' + str(i)), i) for i in range(11,20)], dtype=dt)

fig, ax = plt.subplots(figsize=(18,8), dpi=300)
ax.plot_date(data['date'], data['count'])
#ax.set_xlim( [mdates.date2num( (data['date'][0] - np.timedelta64(1, 'D')).astype(DT) ),
               mdates.date2num( (data['date'][-1] + np.timedelta64(1, 'D')).astype(DT) )]);
  1. With the last line commented out I get a plot but with the x labels shifted to the right of 1 day. 在最后一行被注释掉的情况下,我得到了一个图,但是x标签移到了1天的右侧。
    在此处输入图片说明

  2. When I try to set the x limits to the day before the first day of the data and to the day after the last day of the data the limits are correctly setted but I lose the data points 当我尝试将x限制设置为数据第一天的前一天和最后一天的第二天时,正确设置了限制,但是丢失了数据点 在此处输入图片说明

I replicated the behaviour that you see and it appears that matplotlib does not recognise the numpy datetime64 type. 我复制了您看到的行为,并且看来matplotlib无法识别numpy datetime64类型。

This works - converting the np.datetime64 to a standard python datetime object: 这有效-将np.datetime64转换为标准的python datetime对象:

import datetime
ax.plot_date([d.astype(datetime.datetime) for d in data['date']], data['count'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM