0

I need help with the following issue: I am trying to plot some data using jupyter notebook in the matplotlib notebook mode. The x-values are time data in seconds, y-values are numpy.float64. I then convert the x-values to string values in the format hour:minutes:seconds.decimals.

I want to plot my data in terms of the time in seconds and be able to add the string format of time under the first labels. Also I wish to zoom my plot (using the matplotlib notebook mode on jupyter notebook), as the first labels will automatically adjust to the new tick locations, I want the secondary (string format) labels to adjust as well.

My data :

%matplotlib notebook
import numpy as np
x = np.arange(32349, 32359, 1/10) # time format in seconds
y = np.cos(x)

This is how I convert the time format in the string format (h:min:s)

import time
x_str = [] # time format in strings
for n in range(len(x)):
    decimals = str(round((x[n]-int(x[n])),3))[1:]
    x_str.append(time.strftime('%H:%M:%S', time.gmtime(x[n]))+decimals) # only way I could add the decimals

Does anyone have a solution for me ? Thanks for your time.

SVct
  • 3
  • 4

1 Answers1

0

I seem to have find a solution using ticker.FuncFormatter:

from matplotlib import ticker

def secTo24h(x):
    decimals = str(round(x-int(x),3))[1:]
    xnew = time.strftime('%H:%M:%S', time.gmtime(x))+decimals
    return xnew

plt.figure(constrained_layout=True)
tick_to_24hourSys = lambda x,y: (secTo24h(x))
plt.plot(x, y)
ax = plt.gca()
myFormatter = ticker.FuncFormatter(tick_to_24hourSys)
ax.xaxis.set_major_formatter(myFormatter)
plt.setp(ax.get_xticklabels(), rotation=45)
plt.xlabel('time (24h)')
plt.ylabel('y')
plt.grid()
plt.show()

When zooming, the labels are automatically adjusting.

SVct
  • 3
  • 4