Balraj Boyal
Balraj Boyal

Reputation: 155

MATLAB: changing color of line in a while loop

I am plotting a figure in Matlab. I am doing this in a while loop and I am using the figure to visualize what's happening during the loop.

For every while loop iteration, I want to change the line color so the changes in the while loops are easily monitored.

currently, I have to following code for the plot:

    AOAstr = num2str(AOA);
    figure(2)
    pl = plot(Span_Loc,CPcrit2,'r');
    legendStrs = {'Critical |CPpeak-CPte|'};
    set(pl,'linewidth',1.5);
    hold on
    plot(Span_Loc,CPdiff2)
    legendStrs = [legendStrs, {strcat('Local |CPpeak-CPte|','-','AOA=',AOAstr)}];
    title('Effective angle of attack')
    xlabel('semi-span')
    ylabel('|CPpeak-CPte|')
    legend('boxon')
    legend(legendStrs,'Location','SouthWest'); 

Note: the running variable in the while loop is AOA, hence with every iteration, AOA changes and new data on CPdiff2 and CPcrit2 become available. therefore, I want to plot the old data with a color, hold on, and then plot the data of the second while loop iteration in the same figure but with a different color for plot(Span_Loc,CPdiff2) while also updating the legend.

I cant figure it out, can someone help me?

Thank you!

Upvotes: 1

Views: 522

Answers (2)

Ander Biguri
Ander Biguri

Reputation: 35525

@Thanushan Balakrishnan's answer is good, but you may want to have a higher control over the colors etc.

In my opinion, the best way to visualize these is using colormaps, as they are not just a single color, but a nice visual combinations of colors.

As an example, this code plots thing a bit higher than in the previous iteration each time. Up means larger ii

x=1:100;

y=rand(1,100);

num_iter=90; 
cmap=magma(num_iter); % I used my own colormap but you can use parula or something else
hold on
for ii=0:num_iter-1
    plot(x,y+ii*0.1,'color',cmap(ii+1,:));
end

enter image description here

If you can't know your number of iterations beforehand, I suggest you loop over the colormap.

One nice way of doing this is the following:

x=1:100;
y=rand(1,100);

num_iter=100;
cmap=magma(30); % notice, colormap is smaller
cmap=[cmap; flipud(magma(30))]; % make colormap go back to the first colro again

% now cmap is 60, but iterations are 100!

hold on
for ii=0:num_iter-1
    plot(x,y+ii*0.1,'color',cmap(mod(ii,size(cmap,1))+1,:)); 
end

enter image description here

Upvotes: 0

Thanushan
Thanushan

Reputation: 532

The colour of the line can be specified in plot() as an RGB value ([r, g, b]). The values for the r,g,b should be between 0 and 1. Hence, you can specify the colour as a function of the loop variable AOA.

For example you can specify the line colour like plot(Span_Loc,CPdiff2, 'color', [0, AOA/255, 0]) assuming AOA is never greater than 255.

Upvotes: 1

Related Questions