Abid
Abid

Reputation: 270

Plot from for loop and legend from same loop dont match colors. How can I have them correspond. MATLAB

for j= 1:numfiles;
   plot(A(j,:))
   legendmatrix{j,1}=strcat('Run',num2str(j))
   hold all
end
legend(legendmatrix)

hold all allows me to have different colors for all my curves. However when I use the strings from strcat and display them on the plot, not enough colors are used and they are not assigned to the corresponding curve.

In this case plot 1 is run 1 in the legend, etc... and I want the colors to match

Upvotes: 0

Views: 7017

Answers (2)

Vidar
Vidar

Reputation: 4221

Used Amros example below and made the data easier for visualization of concept and used jet colormap instead to support more than 7 different colors:

%# sample data
N = 15;

x = 1:10;

A = rand(N,10)./2;
A = A + repmat((1:N)',1,10);

%# plot each with a specific color
hold on
clr = jet(N);    %# LINES colormap
for j=1:N
   plot(x, A(j,:), 'Color',clr(j,:))
end
hold off

%# add legend
str = cellstr( num2str((1:N)','Run%d') );
legend(str)

As you can see from the results, the legend is correct, and you can plot a lot more lines: enter image description here

Upvotes: 0

Amro
Amro

Reputation: 124563

Here is a slightly different example:

%# sample data
N = 7;
A = rand(N,10);
x = 1:10;

%# plot each with a specific color
hold on
clr = lines(N);    %# LINES colormap
for j=1:N
   plot(x, A(j,:), 'Color',clr(j,:))
end
hold off

%# add legend
str = cellstr( num2str((1:N)','Run%d') );
legend(str)

screenshot

Note that if N>7, the LINES colormap will start to repeat colors, but you can always specify your own set of colors... You also have the option of using different markers and line-styles to get more visually distinct data.

Upvotes: 0

Related Questions