5

The following is a part of my matlab code. As it's shown, I would like to plot 8 curves in one plot. But I want to make each curve with one unique color. I also want to change the legend so that it changes for each i.

For instance, for i=1 the legend will be gho-1, for i=2 gho-2 and so on. I want it to be automatic because I will change the i sometimes from ex:(i=1:20).

for i=1:8
.
.
.
plot(b,r,'b');
legend(['qho-',num2str(i)]);    
hold on
end

How can I do this?

Hi again,

I have other question: if I have the following

for i=1:8
.
b1=(1:3,:)
b2=(3:6,:)
figure(1);plot(b1,r,'*');
figure(2);plot(b2,r,'*');

Leg{i} = ['qho-',num2str(i)];    

end
legend(Leg)

I got only color legend for the last figure only. not for both.. how can I solve that ?!

Thanks again

YSF
  • 47
  • 1
  • 2
  • 7

2 Answers2

8

Just use hold all instead of hold on and put the legend labels in a cell array

hold all
for i=1:8
    .
    .
    .
    plot(b,r);

    Leg{i} = ['qho-',num2str(i)];    

end
legend(Leg)

See this question for example: Sparse matrix plot matlab


NOTE:

From Matlab R2014b onward, hold on has been modified to act like hold all, i.e. change the colours of the plots each time one is plotted. The docs state that the hold all syntax will be removed in future releases.

Community
  • 1
  • 1
Dan
  • 45,079
  • 17
  • 88
  • 157
  • 1
    `hold all` does limit to the stock 7 colors though, and then loops back through. If you wanted to define your own color set, you could open your figure and `set(gca,'ColorOrder',myColors)`, where `myColors` is an Nx3 matrix of RGB values. – David K Apr 26 '13 at 14:26
  • Hi again, I have other question: if I have the following for i=1:8 . b1=(1:3,:) b2=(3:6,:) figure(1);plot(b1,r,'*'); figure(2);plot(b2,r,'*'); Leg{i} = ['qho-',num2str(i)]; end legend(Leg) I got only color legend for the last figure only. not for both.. how can I solve that ?! Thanks again – YSF Apr 30 '13 at 13:21
  • 1
    Have `Leg1{}` and `Leg2{}` separate and make sure you call `legend(Leg1)` before you call `figure(2)` – Dan Apr 30 '13 at 13:36
  • Hi, that is what I did. but only see different legends and colors in the first figure, and the other one I see one legend only (e.g. gho-1) – YSF Apr 30 '13 at 13:59
7

How about something like:

figure, hold on
N = 8;
h = zeros(N,1);    %# store handle to line graphic objects
clr = lines(N);    %# some colormap
for i=1:N
    %# plot random data
    y = cumsum(randn(100,1));
    h(i) = plot(y, 'Color',clr(i,:));
end
hold off
legend(h, num2str((1:N)','gho-%d'))    %# display legend

plot

Amro
  • 123,847
  • 25
  • 243
  • 454
  • that is great as well. many ways to choose :) :).. thank you very much :) – YSF Apr 26 '13 at 13:00
  • thank you! is there any way to do the trick with `subplot`'s in a loop? 2 subplots on 1 figure, with additional plots for both on every iteration, e.g – soupault Dec 23 '14 at 13:47