Remove the microseconds from matplotlib spectrogram












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









share|improve this question

























  • can you post a data sample?

    – Joe
    Nov 23 '18 at 8: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 8: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 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...

    – PyRar
    Nov 23 '18 at 8:59











  • @Joe it return an error: TypeError: 'datetime.timedelta' object is not subscriptable

    – PyRar
    Nov 23 '18 at 9:37
















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









share|improve this question

























  • can you post a data sample?

    – Joe
    Nov 23 '18 at 8: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 8: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 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...

    – PyRar
    Nov 23 '18 at 8:59











  • @Joe it return an error: TypeError: 'datetime.timedelta' object is not subscriptable

    – PyRar
    Nov 23 '18 at 9:37














0












0








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









share|improve this question
















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






python matplotlib spectrogram






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 9:01







PyRar

















asked Nov 23 '18 at 8:06









PyRarPyRar

1307




1307













  • can you post a data sample?

    – Joe
    Nov 23 '18 at 8: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 8: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 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...

    – PyRar
    Nov 23 '18 at 8:59











  • @Joe it return an error: TypeError: 'datetime.timedelta' object is not subscriptable

    – PyRar
    Nov 23 '18 at 9:37



















  • can you post a data sample?

    – Joe
    Nov 23 '18 at 8: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 8: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 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...

    – PyRar
    Nov 23 '18 at 8:59











  • @Joe it return an error: TypeError: 'datetime.timedelta' object is not subscriptable

    – PyRar
    Nov 23 '18 at 9:37

















can you post a data sample?

– Joe
Nov 23 '18 at 8:07







can you post a data sample?

– Joe
Nov 23 '18 at 8: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 8:10





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 8: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 8:14







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 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...

– PyRar
Nov 23 '18 at 8:59





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 8:59













@Joe it return an error: TypeError: 'datetime.timedelta' object is not subscriptable

– PyRar
Nov 23 '18 at 9:37





@Joe it return an error: TypeError: 'datetime.timedelta' object is not subscriptable

– PyRar
Nov 23 '18 at 9:37












1 Answer
1






active

oldest

votes


















1














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



return str(d)[:7]





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53442765%2fremove-the-microseconds-from-matplotlib-spectrogram%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














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



    return str(d)[:7]





    share|improve this answer




























      1














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



      return str(d)[:7]





      share|improve this answer


























        1












        1








        1







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



        return str(d)[:7]





        share|improve this answer













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



        return str(d)[:7]






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 23 '18 at 10:48









        JoeJoe

        6,12421630




        6,12421630
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53442765%2fremove-the-microseconds-from-matplotlib-spectrogram%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

            Alcedinidae

            Origin of the phrase “under your belt”?