user32882
user32882

Reputation: 5877

Add subsequent plot to legend in matlab

I am currently doing an iterative process where I create a figure, add a plot and then append a legend item. I am doing this as a series of commands but have collected it all in the script below. Please note this cannot be a script since the actual plotting depends on external processes which I must physically iterate since I have no control over them.

>> x = [0:1:10]
>> y1 = []
>> y2 = []
>> y3 = []
>> figure
>> hold on

>> for i = 1:size(x,2)
    y1(i) = x(i)^2
end

>> plot(x,y1,'b')
>> legend('x^2')

>> for i = 1:size(x,2)
    y2(i) = 2*x(i)^2
end

>> plot(x,y2,'r')
>> legend('2*x^2')

>> for i = 1:size(x,2)
    y3(i) = 3*x(i)^2
end

>> plot(x,y3,'g')
>> legend('3*x^2')

As expected this creates a plot with the three functions of interest but a legend containing only the last item. I am not happy with this since when I do this as a series of commands I must each time create a new legend with the old items as well as the new ones. To achieve the desired result the commands must be modified as follows

>> x = [0:1:10]
>> y1 = []
>> y2 = []
>> y3 = []
>> figure
>> hold on

>> for i = 1:size(x,2)
    y1(i) = x(i)^2
end

>> plot(x,y1,'b')
>> legend('x^2')

>> for i = 1:size(x,2)
    y2(i) = 2*x(i)^2
end

>> plot(x,y2,'r')
legend('x^2','2*x^2')

>> for i = 1:size(x,2)
    y3(i) = 3*x(i)^2
end

>> plot(x,y3,'g')
>> legend('x^2', 2*x^2','3*x^2')

What is an efficient way to append the most recently added plot to the current legend without having to rewrite all the previous content? Thanks.

Upvotes: 0

Views: 54

Answers (1)

Wolfie
Wolfie

Reputation: 30047

You cannot just append to a legend, but you can recall it without having to know what came before. This relies on you assigning the legend to a variable, and using its String property to recall previous entries.

% define plotting variables here
x=0:0.1:1; y1=x.^2; y2=2*x.^2; y3=3*x.^2;
% initialise figure   
figure; hold on;
% plot 1
plot(x, y1, 'b');
L = legend('x^2');
% plot 2
plot(x, y2, 'r');
L = legend([L.String, {'2*x^2'}]);
% plot 3
plot(x, y3, 'k');
L = legend([L.String, {'3*x^2'}]);

Result:

plot

Upvotes: 1

Related Questions