0

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.
    enter image description here

  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 enter image description here

2
  • Your first plot looks incorrect. Why does it have dec 10 45 in the x-axis for example? Why the 45? Are you sure your data[date] is the correct date? Commented Dec 12, 2014 at 14:06
  • @Ffisegydd mmm... maybe you are right, in my actual file I am formatting the labels without showing the year so I didn't notice the '45'... but why if I initialize a date with np.datetime64('2014-12-10') it changes the year? Commented Dec 12, 2014 at 14:11

1 Answer 1

2

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'])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.