Reputation: 321
I have this python code for displaying some numbers over time:
import matplotlib.pyplot as plt
import datetime
import numpy as np
x = np.array([datetime.datetime(2013, 9, i).strftime("%Y-%m-%d") for i in range(1,5)],
dtype='datetime64')
y = np.array([1,-1,7,-3])
plt.plot(x,y)
plt.axhline(linewidth=4, color='r')
plt.show()
The resulting graph has the numbers 0.0 to 3.0 on the x-axis:
What is the simplest way to display dates instead of these numbers? Preferably in the format %b %d.
Upvotes: 4
Views: 6165
Reputation: 880987
According to efiring, matplotlib does not support NumPy datetime64 objects (at least not yet). Therefore, convert x
to Python datetime.datetime objects:
x = x.astype(DT.datetime)
Next, you can specify the x-axis tick mark formatter like this:
xfmt = mdates.DateFormatter('%b %d')
ax.xaxis.set_major_formatter(xfmt)
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as DT
import numpy as np
x = np.array([DT.datetime(2013, 9, i).strftime("%Y-%m-%d") for i in range(1,5)],
dtype='datetime64')
x = x.astype(DT.datetime)
y = np.array([1,-1,7,-3])
fig, ax = plt.subplots()
ax.plot(x, y)
ax.axhline(linewidth=4, color='r')
xfmt = mdates.DateFormatter('%b %d')
ax.xaxis.set_major_formatter(xfmt)
plt.show()
Upvotes: 5