Python Question

Add years to x-axis in Matplotlib

I have the following plot which was made using hours in the x-axis:

enter image description here

I would like to change the text on the x-axis to be years rather than hours. So I need years to correspond with specific hours. I've read that this might be done using

plt.xticks(x, my_xticks)
and indexing of my
array, but is not working for me. It would be really appreciated if somebody give me some advice on how to do this. Thank you very much.

Here is an example of my code:

fig_1,ax1 = plt.subplots()
x1 = np.arange(0,129392) #hourly data
x2 = np.linspace(0,129392,5390) #daily data
y_norm = 150.*np.ones([129392,1])
ax1.plot(x1,Data_OBS_h,'k',marker='o',linestyle=' ',label='PM10-1h',linewidth=1.5)

Answer Source

Working with dates

Replace x1 and x2with this:

import datetime

delta_h = datetime.timedelta(hours=1)
start = datetime.datetime(2001, 1, 1)
x1 = [start + x * delta_h for x in range(129392)]
x2 = [start + x * delta_h for x in range(0, 129392, 24)]

Working with time differences

This is useful if you don't have an actual starting date but just a time difference starting from a time zero:

days_per_year = 365.2425
hours_per_day = 24
ax1.xaxis.set_major_locator(plt.MultipleLocator(days_per_year * hours_per_day))
ax1.xaxis.set_ticklabels(range(int(x1[-1] * hours_per_day / days_per_year)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download