Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matplotlib not showing librosa specshow in custom class constructor

I have a custom "waveform"-class which I use for tkinter-applications. Due to testing reasons, i would like to see a spectrogram via librosa.display.specshow() without calling any tkinter-app. Sadly, the following code does not produce an output:

from matplotlib.figure import Figure
from matplotlib.pyplot import show

import librosa as lr
import librosa.display as lrd


class waveform():

    def __init__(self, fp):

        self.sig, self.sr = lr.load(fp, sr=None, res_type="polyphase")

        X = lr.stft(self.sig, n_fft=2**13)
        Xdb = lr.amplitude_to_db(abs(X))

        self.figure = Figure(figsize=(10, 8), dpi=80)
        self.ax = self.figure.add_subplot()
        lrd.specshow(Xdb, sr=self.sr, x_axis="time", y_axis="log", ax=self.ax, cmap='viridis')



if __name__ == "__main__":
    wv = waveform("./noise.wav")
    show()

Are calls to matplotlib (which is what specshow is doing in the background) not rendered when inside of a class constructor?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem seems to come from the fact that you use matplotlib.figure which is not managed by pyplot.
Changing the import works for me

from matplotlib.pyplot import figure
# instead of from matplotlib.figure import Figure
# ...

class waveform():
        # ...
        self.figure = figure(figsize=(10, 8), dpi=80)
        # (Just replaced Figure by figure)
# The rest is the same

However, I am not sure if it fits with your use case, so probably a good read is: https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.show

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading