How to Get Dynamic Legend on Linear Graph in Loop?
Asked Answered
M

1

-2

Diff conditions: how to clear dynamic legends at the end of each iteration; how to remove fitted linear lines at the end of each iteration.

I am trying to extend this answer of the thread Dynamic Legend (Updates in every recursion) to iterate legend on one graph. Proposal to cover dynamic legend on one linear graph

close all; clear all; 

% Test data
aSize=zeros(2,777);
aSize=[[0, 0]' randi(3,2,777)]; % STDEV about 3

x=0:1:180; 

hFig=figure; 

index=1;
while (index<=7); 

    % origo left alone
    aSize(:, index+1) = aSize(:, index+1) + index; % to have linearly increasing trend

    sz=40; 
    legend('-DynamicLegend');
    h = scatter(aSize(1,1:index+1)', aSize(2,1:index+1)', sz, ...
          'MarkerEdgeColor',[0 .5 .5],...
          'MarkerFaceColor',[0 .7 .7],...
          'LineWidth',1.5, ...
          'DisplayName', sprintf('Data'));
    xlabel('width'); ylabel('height');
    hold on; 

    % Optimum
    x=0:1:max( aSize(1, 1:index+1) ); 
    y = x; % assume uniform
    grid on; 
    h1=plot(x,y, 'black', ...
        'DisplayName', sprintf('Optimum'));

    % Fit with R2 linear
    x=aSize(1,1:index+1); 
    b1 = aSize(1,1:index+1)' \ aSize(2,1:index+1)'; 
    yCalc1 = b1 * aSize(1,1:index+1);
    Rsq1 = 1 - sum((y(1:index+1) - yCalc1).^2)/sum((y(1:index+1) - mean(y(1:index+1))).^2)

    % origo needed
    x = [0 x]; 
    yCalc1 = [0 yCalc1]; 
    h2=plot(x(1:index+2)', yCalc1(1:index+2)', '--p', ...
        'DisplayName', sprintf('Fit R2 = %d', Rsq1)); 

    drawnow; 

    index=index+1;

end;

Output unsuccessful where legends are just appended

enter image description here

MATLAB: 2016a
OS: Debian 8.5 6 bit
Linux kernel: 4.6 of backports
Hardware: Asus Zenbook UX303UA

Mag answered 1/10, 2016 at 13:26 Comment(3)
Are you asking how to remove previously plotted data at the end of the loop?Coates
Write hold off before the end of the loop. Does that do what you're looking for?Coates
I removed the answer part from your question. Questions are meant to contain only the question. I judged that your addition didn't give any addition to the already accepted answer you used, so there was no point in having that in the question. If you have something substantial to add, you are free to do so in a new answer.Whiny
C
1

Remove this line legend('-DynamicLegend'); and write it just before the drawnow line and write hold off after that line. So the following will be the lines at the end of your loop.

legend('-DynamicLegend');
drawnow; 
hold off
index=index+1;
Coates answered 1/10, 2016 at 15:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.