Search code examples
matlabhistogramsubplotsuptitle

suptitle Error using axes Invalid axes handle


I am trying to create histograms in a loop. I am creating two figures and want a suptitle above them, but when I do that the title of the subplots doesn't work anymore . This is my code

suptitle('Observation')
for i=1:c:b
    i
    MagObs1=[];
    subplot(b,1,i);
    MagObs1=MagObs(:,i);%0 and 1s
    minMagObs1=min(MagObs1);
    MagObs2=MagObs1(MagObs1>0.001);
    h1=histogram(MagObs2,NumberBins,'Normalization','probability');
    title([num2str(DepthObs(i)),'m']);
    h1.BinLimits=[bottomVel topVel];
    xlabel('Current speed (m/s)');
    ylabel('Frequency');
end

figure(2);% clf;
suptitle('Model')
for i=1:c:b

    subplot(b,1,i);
    
    h2=histogram(MagMatrixH1(i,:),NumberBins,'Normalization','probability')
    title([num2str(DepthObs(i)),'m'])
    h2.BinLimits=[bottomVel topVel]
    xlabel('Current speed (m/s)')
    ylabel('Frequency')
end

and this is the error I get

Error using axes
Invalid axes handle

Error in suptitle (line 98)
axes(haold);

Error in Histogram (line 118)
suptitle('Observation')

This is my output. Normally, every figure has multiple histograms underneath each other, but for this example I only show one. enter image description here

enter image description here

As you can see in the second picture. "Im" should be '300m', could you help me fix this subplots title?


Solution

  • In the (very little) documentation that suptitle has, it says:

    "Use this function after all subplot commands."

    Try adding it in the end of your plotting