How can I change the color of the plot in each iteration in MATLAB?

女生的网名这么多〃 提交于 2019-12-01 19:51:53

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/16236421/how-can-i-change-the-color-of-the-plot-in-each-iteration-in-matlab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!