Search code examples
matlabplotlatextikzspectrogram

Create 2D Spectrogram in Matlab


I am in need of plotting a 2D spectrogram of a signal in Matlab. I need it for a printed assignment, hence the 3D image makes no sense. However, when the signal is plotted using Spectrogram it automatically produces a 3D plot of the signal.

My Code:

Dataset     = 1;            % Dataset to be analysed
N           = 1024;         % Window size
Beta        = 12;           % Kaiser window beta value (small = narrow main lope)
Overlap     = 800;          % Window overlap
Threshold   = -150;         % Minimum magnitude before threshold

spectrogram(Enclosure{Dataset}(1:end),kaiser(N,Beta),Overlap,2048,fs,'MinThreshold',Threshold,'yaxis');

which produces a graph that looks like this:

2D Plot

But it is seen from the top, and the graph is really showing this:

3D plot

The reason why i need it to specifically be 2D (and why i don't settle with a screenshot) is because i am using Matlab2tikz to convert Matlab figures into Tikz figures in LaTex. with the 3D images i get figures of +100 Mb and 2D will reduce the size to <1Mb.


Solution

  • I don't know what version of Matlab you are using but in 2015a you should be able to get a handle to the figure with the 3D plot and change the view angle to 2D:

    view(0,90);
    

    I've also got an example of how you can make your own 2D plot from the outputs of spectrogram() using a similar method:

    x = [0:0.01:100];
    y = sin(5*x);
    y = awgn(y,0.1);
    
    [S,F,T,P] = spectrogram(y,200,0,length(y)*5,100);
    
    [m,n] = size(P);
    
    figure(2)
    surf(F,T,zeros(n,m),P','EdgeColor','none')
    view(0,90)
    xlabel('Frequency')
    ylabel('Time (s)')
    

    The output looks like this:

    enter image description here

    Hopefully since there is no altitude information, the figure size might be smaller but I can't test that since I don't have Matlab2tikz.