Home > Enterprise >  Matplotlib not showing librosa specshow in custom class constructor
Matplotlib not showing librosa specshow in custom class constructor

Time:07-13

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?

CodePudding user response:

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

  • Related