简体   繁体   中英

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.
    在此处输入图片说明

  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 在此处输入图片说明

I replicated the behaviour that you see and it appears that matplotlib does not recognise the numpy datetime64 type.

This works - converting the np.datetime64 to a standard python datetime object:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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