3

I am trying to plot hours in the x-axis [in this picture] using this code

#create a lineplot
fig = plt.figure(figsize=(20,5))
ax = fig.add_subplot()
plt.title('SUBIC-NAIA Air Temp Difference. (C)')
ax.plot(date_rng,NASU_dif)
monthyearFmt = mdates.DateFormatter('%Y-%m-%d-%h')
plt.xaxis_set_major_formatter(monthyearFmt)
plt.xlabel('Time Step (hr)')
plt.ylabel('Air Temperature (m/s)')
plt.legend(loc='upper right', prop={'size': 10})
plt.show()

but I am receiving

AttributeError: module 'matplotlib.pyplot' has no attribute 'xaxis_set_major_formatter'

I have a daterng as my index. How do I solve this one?

DatetimeIndex(['2018-04-22 00:00:00', '2018-04-22 01:00:00', '2018-04-22 02:00:00', '2018-04-22 03:00:00', '2018-04-22 04:00:00', '2018-04-22 05:00:00', '2018-04-22 06:00:00', '2018-04-22 07:00:00', '2018-04-22 08:00:00', '2018-04-22 09:00:00', ... '2018-04-29 15:00:00', '2018-04-29 16:00:00', '2018-04-29 17:00:00', '2018-04-29 18:00:00', '2018-04-29 19:00:00', '2018-04-29 20:00:00', '2018-04-29 21:00:00', '2018-04-29 22:00:00', '2018-04-29 23:00:00', '2018-04-30 00:00:00'], dtype='datetime64[ns]', length=193, freq='H')

kaelel18
  • 31
  • 1
  • 2
  • Does this answer your question? [Changing the formatting of a datetime axis in matplotlib](https://stackoverflow.com/questions/43968985/changing-the-formatting-of-a-datetime-axis-in-matplotlib) – Trenton McKinney Apr 08 '20 at 17:31

2 Answers2

3

Find the set_major_formatter method on the Axis object (e.g. ax.xaxis).

ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d-%h'))

If you don't use subplots, you can access the axis object via the gca() method (get current axis)

from matplotlib import pyplot as plt
import matplotlib.dates as mdates
    
plt.plot(... 

ax = plt.gca()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d-%h'))
Tim Van Laer
  • 2,434
  • 26
  • 30
0

It should be xaxis.set_major_formatter

Also, xaxis is property of ax. So you could do

ax.xaxis.set_major_formatter(monthyearFmt)
Tim Van Laer
  • 2,434
  • 26
  • 30
Jussi Nurminen
  • 2,257
  • 1
  • 9
  • 16
  • 1
    Hi, Thanks for the response. I did not notice the '_' part. Although, even after using xaxis.set_major_formatter, I get module 'matplotlib.pyplot' has no attribute 'xaxis' – kaelel18 Mar 02 '20 at 08:35
  • @kaelel18 mind the `ax`. `xaxis` is a property of axes not `pyplot`. – Tim Van Laer Nov 16 '21 at 09:04