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()
6
  • can you post a data sample? Commented Nov 23, 2018 at 8:07
  • Hello @Joe! Not quite. It's a ".wav" file with different audio sounds. But I'm not allowed to share it :( Commented Nov 23, 2018 at 8:10
  • You can try with something like this: majorFormatter = matplotlib.dates.DateFormatter('%H:%M:%S') ax.xaxis.set_major_formatter(majorFormatter) Commented Nov 23, 2018 at 8: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... Commented Nov 23, 2018 at 8:59
  • @Joe it return an error: TypeError: 'datetime.timedelta' object is not subscriptable Commented Nov 23, 2018 at 9:37

1 Answer 1

1

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

return str(d)[:7]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.