0

So I've represented a spectrogram for a relatively long video(15 minutes). On the time axis, I've got data points at each 3 minute and 20 seconds. This is my spectrogram: enter image description here

I would like to have data point on the x axis for every second. I've tries to modify the function timeTicks from the code, but it doesn't work. As an alternative, I've seen that I could zoom in on my spectrogram, but I can't seem to get it to work.

This is the code:

import matplotlib.pyplot as plt
import scipy.io.wavfile as wavfile

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")

# Prettify
import matplotlib
import datetime

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)
ax.xaxis.set_major_locator(ticker.IndexLocator(base=180, offset=60))
plt.show()

Edit: The present spectogram: enter image description here

PyRar
  • 539
  • 1
  • 4
  • 21
  • `set_major_formatter` only controls how each tick label is written. To control where the ticks are, you need to `set_major_locator` with a tick locator from `matplotlib.dates`. – Joooeey Nov 23 '18 at 00:08
  • and if you don't want labels on all your ticks, use `set_minor_locator`. A label on every second would be too much. – Joooeey Nov 23 '18 at 00:09
  • Thank you for your response @Joooeey! Can't seem to get it done... I've added this line of code: "ax.xaxis.set_major_locator(ticker.IndexLocator(base=180, offset=60))". I have a weird value after the seconds on the x value. Something like ".001415" and I don't know how to get rid of it. I'll attach a new picture with the present spectrogram. – PyRar Nov 23 '18 at 05:36
  • Try: `from matplotlib import dates` and then `ax.xaxis.set_major_locator(dates.MinuteLocator(interval=2))` and `ax.xaxis.set_minor_locator(dates.SecondLocator())`. – Joooeey Nov 23 '18 at 17:00
  • I don't know what the issue with the IndexLocator is, but you can hide the problem by not displaying fractions of a second: `ax.xaxis.set_major_formatter(dates.DateFormatter('%H:%M:%S')` – Joooeey Nov 23 '18 at 17:06

0 Answers0