How to show dates when building in matplotlib.pyplot?

I have this python code to display 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 numbers from 0.0 to 3.0 along the x axis:

enter image description here

What is the easiest way to display dates instead of these numbers? Preferably in the format% b% d.

+4
source share
1 answer

According to efiring , matplotlib does not support NumPy datetime64 objects (at least for now). Therefore, convert xdatetime.datetime to Python objects:

x = x.astype(DT.datetime)

Next, you can specify the format of the label label x, 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()

enter image description here

+4
source

Source: https://habr.com/ru/post/1529028/


All Articles