Skip to content Skip to sidebar Skip to footer

How Do I Display Dates When Plotting In Matplotlib.pyplot?

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).strft

Solution 1:

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 inrange(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()

enter image description here

Post a Comment for "How Do I Display Dates When Plotting In Matplotlib.pyplot?"