Issue
I'm trying to plot some data with a datetime64
x-axis:
t = np.arange(np.datetime64('2022-07-19T12:00:00.00'), np.datetime64('2022-07-19T15:00:00.00'), np.timedelta64(1, 'h'))
y = np.random.rand(3)
plt.plot(t, y)
The x-axis shows day, hour, minute. I am not looking to get the high-resolution values (sec, ms), but I would like to see at least the month, and possibly the year. I don't mind if it's an offset on the bottom right corner of the plot.
How do I display the x-axis data with month and year information?
Solution
In the Matplotlib documentation there is an example of setting date tick labels using the default, concise, and manual date formatter. I suspect you will need to setup a manual formatter with your specific options.
Copy pasting the example here but see the link/docs for more information:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook
# Load a numpy structured array from yahoo csv data with fields date, open,
# close, volume, adj_close from the mpl-data/example directory. This array
# stores the date as an np.datetime64 with a day unit ('D') in the 'date'
# column.
data = cbook.get_sample_data('goog.npz', np_load=True)['price_data']
fig, axs = plt.subplots(3, 1, figsize=(6.4, 7), constrained_layout=True)
# common to all three:
for ax in axs:
ax.plot('date', 'adj_close', data=data)
# Major ticks every half year, minor ticks every month,
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=(1, 7)))
ax.xaxis.set_minor_locator(mdates.MonthLocator())
ax.grid(True)
ax.set_ylabel(r'Price [\$]')
# different formats:
ax = axs[0]
ax.set_title('DefaultFormatter', loc='left', y=0.85, x=0.02, fontsize='medium')
ax = axs[1]
ax.set_title('ConciseFormatter', loc='left', y=0.85, x=0.02, fontsize='medium')
ax.xaxis.set_major_formatter(
mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))
ax = axs[2]
ax.set_title('Manual DateFormatter', loc='left', y=0.85, x=0.02,
fontsize='medium')
# Text in the x axis will be displayed in 'YYYY-mm' format.
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
# Rotates and right-aligns the x labels so they don't crowd each other.
for label in ax.get_xticklabels(which='major'):
label.set(rotation=30, horizontalalignment='right')
plt.show()
Answered By - Aero Engy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.