Python x axis datetime with numpy array and 2 labels type

438 Views Asked by At

I was using obspy to plot seismogram, but when you want to customize a little the plot you must use matplotlib. But this way I don't succeed to have a x axis using date time, with a first label display the all date, then only seconds (or %M:%S eventually).

Here the plot using obspy : enter image description here

See the date time axe.

And here my plot using matplotlib :

enter image description here

How to obtain same time axe than previous graphe ?

And finally the code for the matplotlib plot :

trz = st[2].copy()
tr=trz.trim(starttime=t0, endtime=(t0+float(dur)), nearest_sample=True)
tr.filter("bandpass", freqmin=float(flow), freqmax=float(fhigh), corners=2, zerophase=True)
t = np.arange(0, tr.stats.npts / tr.stats.sampling_rate, tr.stats.delta)

label=(tr.stats.network + '.' + tr.stats.station + '.' + tr.stats.location + '.' + tr.stats.channel)

fig, ax = plt.subplots(1,1,figsize=(18,10), dpi=200)
ax.plot(t,tr.data, 'r', label=label)
ax.set_title('Évènement du '+str(date)+'T'+str(hr)+' station : '+str(sta) + '_' + tr.stats.channel)
ax.xaxis.grid(True, which='major', color='g', linestyle='dotted', linewidth=0.3)
ax.yaxis.grid(True, which='major', color='g', linestyle='dotted', linewidth=0.3)
ax.legend(loc='upper left', ncol=4)
ax.set_xlim(tr.stats.starttime,tr.stats.endtime)

formatter = mdates.DateFormatter("%H-%M-%S")
ax.xaxis.set_major_formatter(formatter)
locator = mdates.HourLocator()
ax.xaxis.set_major_locator(locator)
1

There are 1 best solutions below

4
On

Using the set_xlabel() could be a solution (thanks DPM) but it seem that the trace axis is not sinchronized with the data.

Finally using xlim solve the date format (?), then using matplotlib datesformatter to custom interval.

ax.set_xlim((pd.to_datetime(str(tr.stats.starttime))),(pd.to_datetime(str(tr.stats.endtime))))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
ax.xaxis.set_major_locator(mdates.SecondLocator())

And the result :

enter image description here

But, I just can't figure how to have the first label on the date that using the all format (%Y-%m-%dT%H:%M:%S), but maybe that is not so important ...