0

I'm trying to convert the x-axis ticks from samples to time in the format mm:ss.decimals. The idea is that one second contains fs=44100 samples, so the conversion should be something like

time.strftime('%S.{}'.format(sample/44.1%1000), time.gmtime(sample/44.1/1000.0)))

Here's the whole code:

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import time
import os
import librosa

filename = 'path_to_your_waveform'
s, fs = librosa.load(filename, sr=44100, mono=False)
s=s[0,0:2*fs]

formatter = matplotlib.ticker.FuncFormatter(lambda sample, x: time.strftime('%S.{}'.format(sample/44.1%1000), time.gmtime(sample/44.1/1000.0)))

t_tot = np.arange(0, len(s), 1)
fig, axs = plt.subplots(2, 1, figsize=(10, 10))
for i in np.arange(0,2,1):

    plt.rcParams["agg.path.chunksize"] = 10000
    axs[i].plot(t_tot, s, color='b', linestyle='-')
    axs[i].xaxis.set_major_locator(MultipleLocator(fs/2))
    axs[i].xaxis.set_major_formatter(formatter)

plt.savefig(os.path.join(os.getcwd(), 'name'))

In the figure below you can see that the x-axis ticks do not make sense (the whole file is cut to exactly 2 seconds).

enter image description here

17
  • Please try to explain the idea behind time.strftime('%M:%S:{}'.format(ms%fs), time.gmtime(ms//fs)). This will either directly lead you to see where you're wrong, or at least allow someone to answer this. Commented Oct 17, 2019 at 12:11
  • I have just added this part. Commented Oct 17, 2019 at 12:31
  • Not sure I understand the logic. Why is it not something like time.strftime('%M:%S:%f', time.gmtime(ms/fs))? Commented Oct 17, 2019 at 12:48
  • It might be closer to the solution, but it is shown on the plot like 00:00:f Commented Oct 17, 2019 at 12:56
  • Apparently I'm not the only one with the same issue: stackoverflow.com/questions/48215948/… Commented Oct 17, 2019 at 13:04

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.