Reputation: 25
I have the following plot which was made using hours in the x-axis:
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 x
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)
ax1.plot(x2,Data_OBS,'r',linestyle='-',label='PM10-24h',linewidth=1.5)
ax1.plot(x1,y_norm,'b',linestyle='-',label='standard',linewidth=1.5)
Upvotes: 1
Views: 605
Reputation: 85492
Replace x1
and x2
with 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)]
This is useful if you don't have an actual starting date but just a time difference starting from a time zero:
import math
days_per_year = 365.2425
hours_per_day = 24
ax1.xaxis.set_major_locator(plt.FixedLocator(
range(0, x1[-1], math.ceil(hours_per_day * days_per_year))))
ax1.xaxis.set_ticklabels(range(math.ceil(x1[-1] / (hours_per_day * days_per_year))))
Upvotes: 1
Reputation: 1293
Change the x-axis to datetime objects, and then simply call
plt.plot(x,y)
plt.gcf().autofmt_xdate()
There are also manual (but unfortunate) ways of doing this, which I'll edit in if that does not work.
Upvotes: 2