0

I've been trying to plot an spectogram based on a wav file of 15 minutes lenght. I think I managed to do this, but I can't remove the microseconds from my x axis ( time axis). Any help with this, please?

This is the spectrogram obtained:

enter image description here

This is my code:

import matplotlib.pyplot as plt
import scipy.io.wavfile as wavfile
import matplotlib.ticker as ticker
from matplotlib.dates import DateFormatter, MinuteLocator
import time 
# Prettify
import matplotlib
import datetime
matplotlib.rc('figure', figsize=(17, 5))

cmap = plt.get_cmap('plasma') # this may fail on older versions of matplotlib
vmin = -40  # hide anything below -40 dB
cmap.set_under(color='k', alpha=None)

rate, frames = wavfile.read("audio_test.wav")
fig, ax = plt.subplots()
pxx, freq, t, cax = ax.specgram(frames[:, 0], # first channel
                                Fs=rate,      # to get frequency axis in Hz
                                cmap=cmap, vmin=vmin)
cbar = fig.colorbar(cax)
cbar.set_label('Intensity dB')
ax.axis("tight")



ax.set_xlabel('time h:mm:ss')
ax.set_ylabel('frequency kHz')

scale = 1e3                     # KHz
ticks = matplotlib.ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale))
ax.yaxis.set_major_formatter(ticks)

def timeTicks(x, pos):
    d = datetime.timedelta(seconds=x)
    return str(d)
#formatter = matplotlib.ticker.FuncFormatter(timeTicks)
#ax.xaxis.set_major_formatter(formatter)

majorFormatter = matplotlib.dates.DateFormatter('%H:%M:%S') 
ax.xaxis.set_major_formatter(majorFormatter)
ax.xaxis.set_major_locator(ticker.IndexLocator(base=120, offset=60))
#ax.text(0.0, 0.1, "IndexLocator(base=0.5, offset=0.25)",
#        fontsize=14, transform=ax.transAxes)
plt.show()
PyRar
  • 539
  • 1
  • 4
  • 21
  • can you post a data sample? – Joe Nov 23 '18 at 08:07
  • Hello @Joe! Not quite. It's a ".wav" file with different audio sounds. But I'm not allowed to share it :( – PyRar Nov 23 '18 at 08:10
  • You can try with something like this: `majorFormatter = matplotlib.dates.DateFormatter('%H:%M:%S')` `ax.xaxis.set_major_formatter(majorFormatter)` – Joe Nov 23 '18 at 08:14
  • Thank you @Joe ! It kind of works. But it shows me only "00:02:05" on the time axis. I'll update the photo of the spectrogram and the code. Don't know why it does this... – PyRar Nov 23 '18 at 08:59
  • @Joe it return an error: TypeError: 'datetime.timedelta' object is not subscriptable – PyRar Nov 23 '18 at 09:37
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/184132/discussion-between-joe-and-user7362809). – Joe Nov 23 '18 at 09:37

1 Answers1

1

Using the code before your edit, you can change the return of def timeTicks(x, pos) in:

return str(d)[:7]
Joe
  • 12,057
  • 5
  • 39
  • 55