MATLAB Answers

## How to adjust the legend for a variable number of plots?

Asked by John

### John (view profile)

on 22 Jan 2015
Latest activity Commented on by Image Analyst

### Image Analyst (view profile)

on 23 Jan 2015
Accepted Answer by Image Analyst

### Image Analyst (view profile)

In each figure I have a variable number of plots. However, in the legend I have all the plots. For instance, in the very first figure, I would want only one plot. How can I adjust this?
clc;
clear all;
a=[1/2,1/3,1/4];
l=-0.1:.05:.1;
p = @(x,a,l) 1/3.*(exp(x.^(a))-1)./(exp(x.^(a))+1) + l;
x=linspace(0,.2,101);
for k2 = 1:length(l)
figure(k2)
for k1 = 1:length(a)
plot(x, p(x,a(k1),l(k2)))
hold all
ar{k1} = sprintf('a = %s',rats(a(k1),3));
end
grid
axis([0 .21 0 .25])
hold off
legend(ar, 'Location','best')
end

#### 0 Comments

Sign in to comment.

## 1 Answer

### Image Analyst (view profile)

Answer by Image Analyst

### Image Analyst (view profile)

on 22 Jan 2015
Accepted Answer

You need to check if any p are greater than 0. Those elements < 0 would be not shown since you've set the min y value to 0.
clc;
clear all;
a=[1/2,1/3,1/4];
l=-0.1:.05:.1;
p = @(x,a,l) 1/3.*(exp(x.^(a))-1)./(exp(x.^(a))+1) + l;
x=linspace(0,.2,101);
for k2 = 1:length(l)
figure(k2)
legendCounter = 1;
for k1 = 1:length(a)
pValues = p(x,a(k1),l(k2));
plot(x, pValues)
drawnow;
hold all
if any(pValues >= 0)
ar{legendCounter} = sprintf('a = %s',rats(a(k1),3));
legendCounter = legendCounter + 1;
end
end
grid
axis([0 .21 0 .25])
hold off
legend(ar, 'Location','best')
end
You need to make the colors match for the legend and the plot. It's getting later here so I'll let you do that.

#### 4 Comments

Show 1 older comment
Image Analyst

### Image Analyst (view profile)

on 23 Jan 2015
Not sure what that did, other than mess up the indenting, but whatever...as long as it works. Thanks for Accepting.
John

### John (view profile)

on 23 Jan 2015
The indentation got messy, but now it plots if positive. So those that do not show up in the positive quadrant do not get plotted and hence do not appear at the legend.
Image Analyst

### Image Analyst (view profile)

on 23 Jan 2015
Oh, I see now. You moved the plot inside the if. I guess that's more efficient. I just didn't notice because you set up the axis limits so that negative parts don't show up anyway. By the way, what I always do before posting is to type control-a, control-i in the MATLAB editor to fix the indenting before pasting it here.

Sign in to comment.